ContentControl 上的绑定内容在 DataTemplateSelector 中为 null

Czo*_*zoo 3 c# data-binding xaml contentcontrol windows-runtime

我必须在我的主页上插入 SVG 徽标作为类别名称,每个类别都有其徽标。它们在App.xaml中定义的DataTemplates,我包括他们在我的主页ContentControlDataTemplateSelector显示正确的标志(列入标识工作的无模板选择,但我需要它dinamically包括在内)。

这是主页上的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>
Run Code Online (Sandbox Code Playgroud)

这是我的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是Content="{Binding Category.Name}"似乎不起作用,因为object item我得到的DataTemplateSelector是空的。

我确定它应该可以工作,因为起初我有一个TextBlock具有相同绑定的并且它正确显示了类别名称。

我也尝试在 上使用样式进行绑定,ContentControl但它没有改变任何东西。

我做错什么了吗 ?

谢谢

Czo*_*zoo 5

好的,最后找到了答案:

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

if (category == null)
{
    return null;
}
Run Code Online (Sandbox Code Playgroud)

DataTemplateSelector一次我的数据被初始化之前(因此我没有类别绑定)和第二次用初始化并绑定到我的视图的类别被调用。