3

我必须在主页上插入 SVG 徽标作为类别名称,每个类别都有其徽标。它们在 app.xaml 中定义为DataTemplates,我将它们包含在我的主页中ContentControlDataTemplateSelector以显示正确的徽标(徽标的包含在没有模板选择器的情况下工作,但我需要动态包含它)。

这是主页上的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}"似乎不起作用,因为object item我得到的那个DataTemplateSelector是空的。

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

I also tried binding using a style on the ContentControl but it didn't change anything.

Did I do something wrong ?

Thanks

4

1 回答 1

5

Ok found the answer in the end :

I had to check if my item was null in the template selector

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

The DataTemplateSelector is called once before my data is initialized (thus I have no category to bind) and a second time with the categories initialized and binded to my view.

于 2013-06-20T13:53:44.137 回答