ContentControl不会更改内容-从未调用过的函数 [英] ContentControl does not change the content - function never called
问题描述
我想通过以下代码动态地从AppBar更改内容:
I want to change my content off an AppBar dynamicly whith this code:
<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];
}
}
但是这种方法被称为神经病。 c $ c> Debug.WriteLine 函数。我的错误在哪里?
But this method is nerver called.Even the Debug.WriteLine
function. Where is my mistake?
推荐答案
在这里发表一些评论之后...
(注意:这是有点笼统,但是我无法更具体地使用一些代码来反映问题)
Just after some comments here...
(note: this is a bit general but I can't be more specific w/o some more code to reflect the issues)
这应该按原样进行-我看不到会产生此问题的任何问题(我快速检查了相似的示例,并且它与 .ItemsSource = new List< string> {...}
一起很好地工作。
This should work 'as is' - I don't see any problems that would produce that (I check with similar example fast and it works well with .ItemsSource = new List<string>{...}
.
所以这不是罪魁祸首-但这并没有伤害我的建议-对属性进行适当的MVVM绑定,使列表 ObservableCollection<>
-并且始终建议使用更高级别的
对象(而不只是 string
)作为您的商品(在很多情况下有助于解决类似的问题-该对象实现 INotifyPropertyChanged
等-并在那里绑定属性,而不是整个对象)。
So that's not the culprit - but it doesn't hurt what I suggested - make a proper MVVM binding to properties, make the list ObservableCollection<>
- and also it's always recommended to have a more higher-level
objects (instead of just string
) as your items (helps in many cases with binding with similar issues - that object implements INotifyPropertyChanged
etc. - and you bind to a 'property' there, not the entire object).
另一个错误也暗示了一些问题。
The other error suggests some issues as well.
最后将两个contentControl绑定在一起-您通常不需要此类事件。您可以直接从样式或XAML中使用 Triggers
-但大多数情况下,只需将两者都绑定到视图模型中的一个属性,并处理该属性中的更改 设定者。
And lastly to bind two contentControls together - you don't normally need events as such. You can use Triggers
from the style or XAML directly - but most of the time just bind both to a property in the view-model - and handle the 'change' in your property 'setter'.
您应该放一个重复的小引物-谁知道它可以帮助您意识到自己在做错什么。
You should put up a small primer that repeats this - who knows it might help you realize what you're doing wrong.
这篇关于ContentControl不会更改内容-从未调用过的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!