This question has been round my head the last weeks or months, and I don't really know what's the best solution.
With the MVVM patter we use the View Models to expose data to a View. For example, if I want to show to a user the details of a product I will create certain propeties inside the View Model and populate them. Then through bindings, the view will be able to get the data from those properties. Something like this:
<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>
In the view model I will retrieve the data that I want to display. I will get this data like a Product DTO, which will have the needed properties in the view.
this.productDTO = getData();
So my question is, can we bind directy from the view model to the dto? View Model:
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; }
}
I have the idea that exposing the DTO is not a good thing.. but if It will save me from having to map all the properties from the DTO to the view model..
If you do not need to 'shape' your DTO in order to bind your view, there is absolutely nothing wrong with exposing your DTO directly to your view. You can always introduce a view model at some point in the future if required.
You can also use patterns like the mini-ViewModel (which I describe on my blog) to add localised View Models to shape parts of your model.
Wrapping your DTO in a view model as you have done, adds code that does not provide any benefit. It increases the size of your code-base and the risk of bugs.
KISS - Keep it simple!
private ProductDTO product;
public string ProductName
{
get { return this.product.Name; }
set { this.product.Name = value; }
}
the only problem i can see is that, when your Name property of your dto changed its not simply reflected in your UI. so i would prefer this:
public ProductDTO Product {...}
<TextBlock Text="{Binding Path=Product.Name}" />
this of course requires that your DTO implement INotifyPropertyChanged
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With