ContentControl上绑定的内容在DataTemplateSelector中为空。

3
我需要在主页上插入SVG标志作为类别名称,每个类别都有它自己的标志。它们被定义在app.xaml中作为DataTemplates,并且我在主页上使用ContentControl包含它们,并使用DataTemplateSelector来显示正确的标志(如果不使用模板选择器,则标志的包含工作正常,但我需要动态包含)。以下是主页上的XAML代码:
<GroupStyle>
    <GroupStyle.HeaderTemplate>
        <DataTemplate>
            <Grid Margin="1,0,0,6"  Name="CategoryName">
                <Button AutomationProperties.Name="Group Title" Click="Category_Click" Style="{StaticResource TextPrimaryButtonStyle}">
                    <ContentControl Name="CategoryLogo" Content="{Binding Category.Name}" ContentTemplateSelector="{StaticResource LogoTemplateSelector}" IsHitTestVisible="True" Margin="3,-7,10,10"/>
                </Button>
            </Grid>
        </DataTemplate>
    </GroupStyle.HeaderTemplate>
</GroupStyle>

这里是我的 DataTemplateSelector

public class LogoTemplateSelector : DataTemplateSelector
{
    public string DefaultTemplateKey { get; set; }

    protected override DataTemplate SelectTemplateCore(object item, Windows.UI.Xaml.DependencyObject container)
    {
        var category = item as String;
        DataTemplate dt = null;

        switch (category)
        {
            case "Category1": dt = FindTemplate(App.Current.Resources, "Logo1");
                break;
            case "Category2": dt = FindTemplate(App.Current.Resources, "Logo2");
                break;
            case "Category3": dt = FindTemplate(App.Current.Resources, "Logo3");
                break;
            case "Category4": dt = FindTemplate(App.Current.Resources, "Logo4");
                break;
            default: dt = FindTemplate(App.Current.Resources, "Logo1");
                break;
        }

        return dt;
    }

    private static DataTemplate FindTemplate(object source, string key)
    {
        var fe = source as FrameworkElement;
        object obj;
        ResourceDictionary rd = fe != null ? fe.Resources : App.Current.Resources;
        if (rd.TryGetValue(key, out obj))
        {
            DataTemplate dt = obj as DataTemplate;
            if (dt != null)
            {
            return dt;
            }
        }
        return null;
    }
}

我的问题是,Content="{Binding Category.Name}" 似乎不起作用,因为我在 DataTemplateSelector 中得到的 object item 是空的。
我确定它应该可以工作,因为一开始我有一个使用相同绑定的 TextBlock,它正确地显示了类别名称。
我还尝试使用 ContentControl 上的样式进行绑定,但没有改变任何东西。
我做错了什么吗?
谢谢。
1个回答

5

最终我找到了答案:

我需要在模板选择器中检查我的项目是否为空

if (category == null)
{
    return null;
}

DataTemplateSelector 在我的数据初始化之前仅被调用一次(因此我没有类别绑定),然后在类别已初始化并绑定到我的视图的情况下再次调用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接