【发布时间】:2013-04-27 12:55:25
【问题描述】:
我想使用以下代码动态更改 AppBar 上的内容:
<Page.Resources>
<local:AppBarSelector x:Key="myAppBarSelector"/>
</Page.Resources>
<Page.BottomAppBar>
<AppBar>
<ContentControl Content="{Binding SelectedItem, ElementName=listBox}" ContentTemplateSelector="{StaticResource myAppBarSelector}">
<ContentControl.Resources>
<DataTemplate x:Key="1">
<TextBlock Text="Hallo Welt 1" Foreground="White" />
</DataTemplate>
<DataTemplate x:Key="2">
<TextBlock Text="Hallo Welt 2" Foreground="White" />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
</AppBar>
</Page.BottomAppBar>
这是我的代码:
public class AppBarSelector : DataTemplateSelector
{
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
Debug.WriteLine((string)item);
if (item == null) return base.SelectTemplateCore(item, container);
var contentControl = (ContentControl)container;
var templateKey = (string)item;
return (DataTemplate)contentControl.Resources[templateKey];
}
}
但是这种方法调用起来比较神经。即使是Debug.WriteLine 函数。我的错在哪里?
【问题讨论】:
-
您确定您的项目实际上是一个字符串吗?那时可能是例外。你的项目是你的绑定 ItemsSource 项目。
-
是的,我用以下内容填充 ListView:
listBox.ItemsSource = new List<string> { "1" , "2", "3" , "4"};我有第二个 ContentControl,它使用另一个Page.Resource,但也使用 listView 项的字符串 - 效果很好,但这里没有调用该函数... -
很抱歉怀疑你 :) 你在调试视图中有任何错误吗?又是微不足道的,但您确定它不会“命中” SelectTemplateCore(放置断点,而不仅仅是转储)。
-
我在调试视图中找不到任何错误...该方法在启动应用程序后被调用一次,但随后再也没有被调用:/ 但在第二个 ContentControl.Resources 中(对于主要内容 - 不适用于 AppBar)我收到错误 declared prefix 但我可以编译并运行该应用程序。是这个问题吗?
-
好吧,那是不同的(它进入一次 - 它是“活着的”:) - 这很熟悉。首先,您应该执行正确的 MVVM,因为这通常是问题的根源(在您的情况下并不重要,但是 - 将
ItemsSource设置为绑定到 VM 中的属性 - 这是ObservableCollection<string>(不是 List))。另请查看this。似乎您的 Binding 没有触发(我无法对此进行测试,所以只是给出提示)。最终的解决方案是使用 MultiBinding 并使其“改变”...
标签: xaml windows-8 contentcontrol datatemplateselector