开发者

MVVM computed properties

Whats the recommended way of dealing with computed properties that are basicall开发者_如何转开发y string formatting ? In the View or in the ViewModel? At the moment I've got this in the view:

<StackPanel Orientation="Horizontal">
    <TextBlock Style="{StaticResource FootnoteTextStyle}" Text="Free Memory (KB): " />
    <TextBlock Style="{StaticResource FootnoteTextStyle}" Text="{Binding MemoryRemain}" />
    <TextBlock Style="{StaticResource FootnoteTextStyle}" Text=" / " />
    <TextBlock Style="{StaticResource FootnoteTextStyle}" Text="{Binding MemoryTotal}" />
    <TextBlock Style="{StaticResource FootnoteTextStyle}" Text=" (" />
    <TextBlock Style="{StaticResource FootnoteTextStyle}" Text="{Binding MemoryRemainPercent}" />
    <TextBlock Style="{StaticResource FootnoteTextStyle}" Text="%)" />
</StackPanel>

Is it better to put this in the viewmodel as a computed property of type string and then just have a single TextBlock bound to it?


It is also kinda possible to use string.format in XAML. I suppose you could rewrite your xaml to this:

<StackPanel Orientation="Horizontal">
    <TextBlock>
        <TextBlock.Text>
            <MultiBinding StringFormat="Free Memory (KB): {0} / {1} ({2}%)">
                <Binding Path="MemoryRemain" />
                <Binding Path="MemoryTotal" />
                <Binding Path="MemoryRemainPercent" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</StackPanel>

IMO, it's a bit cleaner, because you see the string as a whole, as you would in code. I also agree with slugster and Myles J that the formatting should be done by the view.


I agree with the comment by slugster "formatting any values should be done by the View". I would just add that you could always write a custom converter to take care of the formatting side of things.


I generally create additional properties and put the formatting in the getters in the view model. Its the model of the view and concerned with how something is displayed. I suppose it also makes the display format testable.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜