我做了一个示例演示VS 2010 RC示例项目,因为在我的生产项目中,我使用MVVM发生同样的错误。ContentTemplateSelector只被称为一次显示总是相同的数据模式
在我的示例演示项目中,我只使用代码隐藏没有第三方的依赖,所以你可以在这里下载演示项目并运行它自己:http://www.sendspace.com/file/mwx7wv
现在的问题:当我点击女生/男生按钮它应该切换数据模板,而不是?
我该怎么做?
好,我这里也提供了一个代码片段:
代码隐藏MainWindow.cs:
namespace ContentTemplateSelectorDemo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Person person;
public MainWindow()
{
InitializeComponent();
person = new Person(){ Gender = "xxx"};
person.IsBoy = true;
ContentGrid.DataContext = person;
}
private void btnBoys_Click(object sender, RoutedEventArgs e)
{
person.IsBoy = true;
person.IsGirl = false;
this.ContentGrid.DataContext = person;
}
private void btnGirls_Click(object sender, RoutedEventArgs e)
{
person.IsGirl = true;
person.IsBoy = false;
this.ContentGrid.DataContext = person;
}
}
}
XAML MainWindow.xaml:
<Window x:Class="ContentTemplateSelectorDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ContentTemplateSelectorDemo"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate x:Key="girlsViewTemplate">
<local:UserControl1 />
</DataTemplate>
<DataTemplate x:Key="boysViewTemplate" >
<local:UserControl2 />
</DataTemplate>
<local:PersonDataTemplateSelector x:Key="PersonSelector" />
</Window.Resources>
<Grid x:Name="ContentGrid" >
<StackPanel>
<Button Name="btnGirls" Click="btnGirls_Click">Switch Girls</Button>
<Button Name="btnBoys" Click="btnBoys_Click">Switch Boys</Button>
<ContentControl Content="{Binding}" ContentTemplateSelector="{StaticResource ResourceKey=PersonSelector}" />
</StackPanel>
</Grid>
</Window>
DataTemplateSelector类:
public class PersonDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item,DependencyObject container)
{
if (item is Person)
{
Person person = item as Person;
Window window = Application.Current.MainWindow;
if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(window))
return null;
if (person.IsBoy)
return window.FindResource("boysViewTemplate") as DataTemplate;
if (person.IsGirl)
return window.FindResource("girlsViewTemplate") as DataTemplate;
}
return null;
}
}
:)
更好的职位代码片段,而不是提供下载,人们很可能不会去下载这个吨。 – 2010-04-02 09:17:29
确定编辑我的初始文章! – msfanboy 2010-04-02 10:43:19
确定经过一番调研后: http://joshsmithonwpf.wordpress.com/2007/03/18/updating-the-ui-when-binding-directly-to-business-objects-that-are-modified/ 像乔什在他的代码评论中说:“...这是必要的,因为WPF绑定系统将忽略 \t \t \t // PropertyChanged通知如果属性返回与之前相同的对象引用...” 我不能返回相同的对象,而不是我必须在按钮事件处理程序中重新创建Person对象,如: ... = new Person(){IsBoy = true,IsGirl = false}等... 然后它的工作。 谢谢乔希! – msfanboy 2010-04-03 10:29:25