在运行时更改DataTemplates

时间:2010-10-20 19:27:59

标签: wpf silverlight

我希望能够在运行时换出数据模板,但没有

FindResource("fdds") as DataTemplate

我见过的代码类型很多。我希望能够根据我的ViewModel中的属性绑定模板以查找资源。从概念上讲,我希望能够做到这一点,但编译器显然不喜欢它:

 ... ItemTemplate="{StaticResource {Binding Path=VMTemplate}}">

然后其他命令会改变ViewModel中VMTemplate的值。有没有办法做这样的事情?

2 个答案:

答案 0 :(得分:2)

StaticResource扩展是在解析XAML时立即查找,这意味着资源必须出现在应用程序的开头。为了动态设置模板,您必须执行与第一行相似的操作。

我已经看到的一种可能性是使DataTemplate具有扩展ContentControl的自定义控件,该控件具有多个DataTemplate属性,然后可以根据View Model中的绑定值选择不同的模板。 / p>

答案 1 :(得分:2)

这似乎是“最好的”赌注:

http://www.e-pedro.com/2009/06/using-data-binding-with-static-resources-in-wpf/

当然,您可以手动将实际模板作为参数传递给其他命令:

<Button Width="50" Command="{Binding ChangeTemplateCommand}" CommandParameter="{StaticResource vmDataTemplate}">White</Button>
<Button Width="50" Command="{Binding ChangeTemplateCommand}" CommandParameter="{StaticResource vmDataTemplate2}">Lavender</Button>

<ListBox x:Name="bookListBox" Grid.Row="0" ItemsSource="{Binding Path=BookSource}" ItemTemplate="{Binding Path=ItemSourceTemplate}">

然后在ViewModel中:

ChangeTemplateCommand = new RelayCommand(template => {
    this.ItemSourceTemplate = (DataTemplate)template;
    PropertyChanged(this, new PropertyChangedEventArgs("ItemSourceTemplate"));
});