【问题标题】:Binded content on ContentControl is null in DataTemplateSelectorContentControl 上的绑定内容在 DataTemplateSelector 中为空
【发布时间】:2013-06-19 13:01:13
【问题描述】:

我必须在我的主页上插入 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}" 似乎不起作用,因为我在DataTemplateSelector 中获得的object item 为空。

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

我还尝试使用ContentControl 上的样式进行绑定,但没有任何改变。

我是不是做错了什么?

谢谢

【问题讨论】:

    标签: c# xaml data-binding windows-runtime contentcontrol


    【解决方案1】:

    好的,最终找到了答案:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      • 2012-12-20
      相关资源
      最近更新 更多