Xaml ContentControl不会更改内容-从未调用过函数

Xaml ContentControl不会更改内容-从未调用过函数,xaml,windows-8,contentcontrol,datatemplateselector,Xaml,Windows 8,Contentcontrol,Datatemplateselector,我想使用以下代码动态更改AppBar中的内容: <Page.Resources> <local:AppBarSelector x:Key="myAppBarSelector"/> </Page.Resources> <Page.BottomAppBar> <AppBar> <ContentControl Content="{Binding SelectedItem, ElementName=lis

我想使用以下代码动态更改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>

但是这个方法没有被调用。甚至
Debug.WriteLine
函数也没有被调用。我的错误在哪里?

刚刚在这里发表了一些评论…
(注意:这有点笼统,但我不能更具体,没有更多的代码来反映问题)

这应该“按原样”工作——我看不出会产生这种情况的任何问题(我用类似的例子快速检查,它在
.ItemsSource=newlist{…}
中运行良好)

所以这不是罪魁祸首——但这并不影响我的建议——创建一个适当的MVVM绑定到属性,创建列表
ObservableCollection
——并且始终建议将更高级的
对象(而不仅仅是
字符串
)作为您的项目(在许多情况下有助于解决类似问题的绑定—该对象实现了
INotifyPropertyChanged
等—并且您绑定到了其中的“属性”,而不是整个对象)

另一个错误也说明了一些问题

最后,要将两个ContentControl绑定在一起,通常不需要事件本身。可以直接从样式或XAML中使用
触发器
,但大多数情况下只需将两者绑定到视图模型中的属性,并处理属性“setter”中的“更改”


你应该用一个小的入门来重复这一点-谁知道它可能会帮助你意识到你做错了什么。

你确定你的项目实际上是一个字符串吗?在这一点上,它可能是例外。你的项目是你的绑定项目资源项目。是的,我在列表视图中填充:
listBox.ItemsSource=新列表{“1”、“2”、“3”、“4”};
我还有第二个ContentControl,它使用另一个
页面。Resource
但也使用listView项的字符串-这很好,但是这里没有调用该函数…很抱歉怀疑您:)调试视图中有任何错误吗?还是很小,但是您确定它没有“命中”SelectTemplateCore吗(放置一个断点,而不仅仅是转储)。我在调试视图中找不到任何错误…该方法在启动应用程序后被调用一次,但之后再也不会被调用:/而是在第二个ContentControl.Resources中(用于主内容-不用于AppBar)我得到了声明错误的前缀,但我可以编译和运行应用程序。这是问题吗?好的,这是不同的(它输入一次-它是“活动的”)-这很熟悉。首先,你应该做正确的MVVM,因为这通常是问题的根源(在您的情况下并不重要,但-设置
ItemsSource
以绑定到VM中的属性-即
observateCollection
(非列表))。另外,请注意。您的绑定似乎没有触发(我无法测试,所以只能给出提示)。最终的解决方案是使用多重绑定并使其“更改”。。。
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];
    }
}