gpt4 book ai didi

xaml - 如何在 Windows 8.1 的 ContentPresenter 中使用模板选择器

转载 作者:行者123 更新时间:2023-12-05 09:22:12 25 4
gpt4 key购买 nike

我有一个 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;
}

}

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

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

最佳答案

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

来自DataTemplateSelector文档:

To define an effective DataTemplateSelector subclass, provide implementations for SelectTemplateCore(Object) and SelectTemplateCore(Object, DependencyObject)

一旦您为 SelectTemplateCore(Object, DependencyObject) 提供实现,它就会被调用。

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

我问谷歌为什么会这样并找到this discussion .来自:

The ContentControl and ContentPresenter appear to be broken in Windows RT when used with a ContentTemplateSelector property bound to a view model. The 'object' parameter to the template selector is always null.

在该讨论的最后还有一个解决此问题的方法。

希望这对您有所帮助。 :)

关于xaml - 如何在 Windows 8.1 的 ContentPresenter 中使用模板选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28102668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com