【问题标题】:How to use template selector within a ContentPresenter in Windows 8.1如何在 Windows 8.1 的 ContentPresenter 中使用模板选择器
【发布时间】:2015-01-23 03:44:39
【问题描述】:

我有一个 Windows 8.1 应用程序。我需要根据某个值选择不同的模板。为此,我在带有静态资源模板选择器的 xaml 中使用 ContentPresenter。

这是我在 xaml 资源中的数据模板和模板选择器

    <DataTemplate x:Key="template1">
        <TextBox Text="Temp 1" />
    </DataTemplate>

    <DataTemplate x:Key="template2">
        <TextBox Text="Temp 2" />
    </DataTemplate>

    <DataTemplate x:Key="template3">
        <TextBox Text="Temp 3" />
    </DataTemplate>

    <template:BalanceTypesTemplateSelector x:Key="MySelector"
                                           Template1="{StaticResource template1}"
                                           Template2="{StaticResource template2}"
                                           Template3="{StaticResource template3}" />

这是我的 ContentPresenter XAML

<ContentPresenter ContentTemplateSelector="{StaticResource MySelector}"
                                                Content="{Binding MyData}" />

这是我的模板选择器代码

public class BalanceTypesTemplateSelector : DataTemplateSelector
{
    public DataTemplate Template1 { get; set; }
    public DataTemplate Template2 { get; set; }
    public DataTemplate Template3 { get; set; }

    protected override DataTemplate SelectTemplateCore(object item)
    {
            var type = item.ToString();
            switch (type)
            {
                case "t1":
                    return Template1;
                case "t2":
                    return Template1;
                case "t3":
                    return Template3;
                default:
                    throw new NotSupportedException();
            }
        }

        return null;
    }

}

但它根本没有命中模板选择器代码。当我运行应用程序时,绑定的字符串直接显示在显示屏上。

如果有人指出我正确的方向,我会很高兴。提前致谢。

【问题讨论】:

  • 你能试试 ContentControl 代替 ContentPresenter 吗?

标签: xaml winrt-xaml windows-8.1 win-universal-app


【解决方案1】:

基本上,您只是覆盖SelectTemplateCore 重载之一。

来自DataTemplateSelector 文档:

要定义有效的 DataTemplateSelector 子类,请提供 SelectTemplateCore(Object)SelectTemplateCore(Object, DependencyObject) 的实现

一旦您提供了SelectTemplateCore(Object, DependencyObject) 的实现,它将被调用。

我尝试这样做,但遇到了另一个问题 - 对象始终为 null(而不是 ContentPresenter 的 Content/DataContext)。

我问谷歌为什么会这样,发现this discussion。来自它:

当与绑定到视图模型的 ContentTemplateSelector 属性一起使用时,ContentControl 和 ContentPresenter 在 Windows RT 中似乎已损坏。模板选择器的 'object' 参数始终为 null。

在讨论结束时还有解决此问题的方法。

希望这会有所帮助。 :)

【讨论】:

    【解决方案2】:

    使用 ContentControl 而不是 ContentPresenter 对我有用。感谢@KaiBrummund 对我的问题的评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多