是否将我的DTO暴露给被认为不正确的视图?

Asi*_*xea 4 c# silverlight wpf mvvm

在过去几周或几个月里,这个问题一直在我的脑海里,我真的不知道什么是最好的解决方案.

使用MVVM模式,我们使用View Models将数据公开给View.例如,如果我想向用户显示产品的详细信息,我将在视图模型中创建某些属性并填充它们.然后通过绑定,视图将能够从这些属性中获取数据.像这样的东西:

 <StackPanel>
    <TextBlock Text="Prodcut Name:" FontWeight="Bold" />
    <TextBlock Text="{Binding Path=ProductName}" />

    <TextBlock Text="Price:" FontWeight="Bold"/>
    <TextBlock Text="{Binding Path=Price}"/>

    <TextBlock Text="Added Date:"  FontWeight="Bold" />
    <TextBlock Text="{Binding Path=Date}"/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

在视图模型中,我将检索要显示的数据.我将获得像Product DTO这样的数据,它将在视图中具有所需的属性.

 this.productDTO = getData();
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,我们可以将directy从视图模型绑定到dto吗?查看型号:

    private ProductDTO product;

    public string ProductName
    {
        get { return this.product.Name; }
        set { this.product.Name = value; }
    }

    public string Price
    {
        get { return this.product.Price; }
        set { this.product.Price = value; }
    }
Run Code Online (Sandbox Code Playgroud)

我认为暴露DTO并不是一件好事......但是如果它能够让我不必将所有属性从DTO映射到视图模型.

Col*_*inE 5

如果您不需要"塑造"您的DTO以绑定您的视图,那么将DTO直接暴露给您的视图绝对没有错.如果需要,您始终可以在将来的某个时间点引入视图模型.

您还可以使用mini-ViewModel(我在我的博客中描述)等模式添加本地化的View Models来塑造模型的各个部分.

像您一样将DTO包装在视图模型中,添加的代码不会带来任何好处.它增加了代码库的大小和错误的风险.

- 保持简单!


bli*_*eis 5

private ProductDTO product;

public string ProductName
{
    get { return this.product.Name; }
    set { this.product.Name = value; }
}
Run Code Online (Sandbox Code Playgroud)

我能看到的唯一问题是,当您的dto的Name属性发生更改时,它不会简单地反映在您的UI中.所以我更喜欢这个:

public ProductDTO Product {...}

<TextBlock Text="{Binding Path=Product.Name}" />
Run Code Online (Sandbox Code Playgroud)

这当然要求您的DTO实现INotifyPropertyChanged