开发者

Silverlight/WPF Viewmodel Best Practices

Let's say I'm reading some book objects from my data service, and using each result to create a ViewModel for display in, say, a ListBox or a DataGrid.

public class BookViewModel {
    public BookViewModel(DataService.BookResult B) {
        this.CurrentBook = B;

        //other details elided
    }

If this ViewModel has many of the same exact properties as the book object from the data service, are there any good reasons to duplicate all of the needed properties from the DataService.BookResult over to the ViewModel, or is it ok to just store the Dataservice.BookResult object, and bind through it:

            <sdk:DataGridTemplateColumn SortMemberPath="CurrentBook.Title" Header="Title" Width="430">
                <sdk:DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock VerticalAlignment="Center" Margin="5,0,0,0" Text="{Binding CurrentBook.Title}" ToolTipService.ToolTip="{Binding CurrentBook.Title}"></TextBlock>
                    </DataTemplate>
                </sdk:DataGridTemplateColumn.CellTemplate>
            </sdk:DataGridTemplateColumn>

            <sdk:DataGridTemplateColumn Header="Publisher" Width="150">
                <sdk:DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Grid VerticalAlignment="Center" Margin="7,0,0,0">
                            <TextBlock x:Name="publisherText" Visibility="{Binding CurrentBook.Publisher, Converter={StaticResource hasValueConverter}}" Text="{Binding CurrentBook.Publisher}" ToolTipService.ToolTip="{Binding CurrentBook.Publisher}" />
                            <TextBlock Visibility="{Binding Visibility, ElementName=publisherText, Converter={StaticResource visibilityInverter}}" Style="{StaticResource textForNoData}">No开发者_StackOverflow社区 Publisher Info</TextBlock>
                        </Grid>
                    </DataTemplate>
                </sdk:DataGridTemplateColumn.CellTemplate>
            </sdk:DataGridTemplateColumn>

I know this violates the Law of Demeter, and that I should probably just list out all the properties, and have ValueInjecter do the property-mapping minutiae in a factory method, but since this is a pretty small project, where changes to the Data Service are highly unlikely, and the footprint of such changes would be relatively small, are there any Silverlight/WPF-specific reasons why this might or might not be a good idea?


The Law of Demeter constrains the use of methods, not properties. Read-only access to properties in your object model doesn't violate it.

I wouldn't worry about this at all, as long as you're only doing one-way binding and you don't need property-change notification. But lookups of descriptive information about data elements in your view? I don't see an issue with that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜