如何在 Windows 8.1 的 ContentPresenter 中使用模板选择器 [英] How to use template selector within a ContentPresenter in Windows 8.1

查看:17
本文介绍了如何在 Windows 8.1 的 ContentPresenter 中使用模板选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Windows 8.1 application. I have a requirement of selecting different templates based on a certain value. For this purpose I'm using ContentPresenter in the xaml with a Static Resource TemplateSelector.

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

Here's my datatemplates and templateselector in xaml resources

    <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

Here's my ContentPresenter XAML

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

这是我的模板选择器代码

Here's my Template Selector Code

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;
    }

}

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

But it's not hitting the templateselector code at all. The string that is bound is directly displayed on the display when I run the app.

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

I would be glad if some one point me in the right direction. Thanks in Advance.

推荐答案

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

Using ContentControl instead of ContentPresenter is working for me. Thanks @KaiBrummund for his comment on my question.

这篇关于如何在 Windows 8.1 的 ContentPresenter 中使用模板选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆