Silverlight 中的 DataTemplate.DataType 替代方案 [英] DataTemplate.DataType alternative in Silverlight
问题描述
我有一个带有属性 Fields
的视图模型,它是一个 ObservableCollection
.在使用此属性的视图中,我有一个 ItemsControl
,如下所示:
I have a view model with a property Fields
which is an ObservableCollection<FieldVM>
. In the view that uses this property, I have an ItemsControl
like so:
...
<ItemsControl ItemsSource="{Binding Fields}" />
...
FieldVM
是一个抽象类,由TextFieldVM
和EnumFieldVM
等类实现.在运行时,这些 FieldVM
实现被添加到 Fields
属性中,我希望它们与它们关联的视图一起显示在我的视图中.
FieldVM
is an abstract class, implemented by such classes as TextFieldVM
and EnumFieldVM
. During run time, these FieldVM
-implementations get added to the Fields
property and I want them to show up in my view with their associated views.
在 WPF 中,这样做很简单,我一直都在这样做.您只需在适当的资源字典中执行此操作,一切都会按预期进行:
In WPF, doing this is simple, I do it all the time. You just do this in an appropriate resource dictionary, and everything works as expected:
<DataTemplate DataType="{x:Type vm:TextFieldVM}">
<v:TextFieldView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:EnumFieldVM}">
<v:EnumFieldView />
</DataTemplate>
现在,第一次在 Silverlight 中工作,我希望我可以做同样的事情,但是 DataTemplate
没有 DataType
属性.我难住了.这样做的 Silverlight 方式是什么?
Now, working in Silverlight for the first time, I expected I could just do the same thing, but the DataTemplate
doesn't have a DataType
property. I'm stumped. What's the Silverlight-way of doing this?
推荐答案
使用值转换器将类型绑定到每个视图的可见性:
Use a Value Converter to bind the type to the visibility of each view:
<DataTemplate>
<Grid>
<v:EnumFieldView
Visibilty="{Binding Converter={StaticResource ViewVisibilityConverter}, ConverterParameter=Enum}" />
<v:TextFieldView
Visibilty="{Binding Converter={StaticResource ViewVisibilityConverter}, ConverterParameter=Text}" />
</Grid
</DataTemplate>
在ViewVisibilityConverter的ConvertTo中,根据类型切换可见性.
And in the ConvertTo of the ViewVisibilityConverter, switch the visibility based on the type.
另一种看待它的方法是使用不同类型的值转换器从 Application.Resources 返回不同的数据模板.
Another way to look at it would be to use a different type of value converter to return a different data template from the Application.Resources.
<ListBox ItemTemplate="{Binding Converter={StaticResource ItemTemplateFactory}"/>
在 ItemTemplateFactory.Convert() 中:
in ItemTemplateFactory.Convert():
var fieldVM = value as FieldVM;
switch fieldVM.FieldType:
{
case "Text":
return Application.Current.Resources["TextTemplate"] as DataTemplate;
case "Enum":
return Application.Current.Resources["EnumTemplate"] as DataTemplate;
}
这篇关于Silverlight 中的 DataTemplate.DataType 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!