Silverlight中的DataTemplate.DataType替代 [英] DataTemplate.DataType alternative in Silverlight

查看:78
本文介绍了Silverlight中的DataTemplate.DataType替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图模型,其属性为 Fields ,它是 ObservableCollection< FieldVM> 。在使用此属性的视图中,我有一个 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}"/>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆