0

I'm building a WPF user control which displays a simple stacked bar using Rectangles. The data is provided by a DependencyProperty in the viewmodel so I can bind a collection to it. The model looks like this:

public class BarPart {
  public Color Color { get; set; }
  public int Size { get; set; }
}

The view with a fake width binding illustrating the intent:

<ItemsControl ItemsSource="{Binding ElementName=Root, Path=Data}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Rectangle Width="{Binding TotalSize / Size * Root.Width}" Height="30">
                <Rectangle.Fill>
                    <SolidColorBrush Color="{Binding Color}" />
                </Rectangle.Fill>
            </Rectangle>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Of course the size is not in a unit used for display, it can be any number. This means I can't bind directly to Size. Yet the total width of the stacked bars should span the width of the usercontrol. The bound size should be calculated using the sum of the sizes, the size of the BarPart in question, and the total width of the control.

MVVM dictates the viewmodel shouldn't know anything about the view. So where should these calculations and conversions take place?

An IValueConverter can't do the math since it doesn't know the sum of all BarPart sizes combined and doesn't know the total width of the usercontrol to convert to display units.

I'm not sure what other options I have doing strict MVVM.

4

1 回答 1

1

您可以使用MultiBindingwith 转换器,绑定将类似于:

<Binding Path="Size"/>
<Binding ElementName="Root" Path="DataContext.TotalSize"/>
<Binding ElementName="Root" Path="ActualWidth"/>

包含条形图的视图模型应计算TotalSize.

(为了保持更新,您需要订阅所有条的属性更改,以便您可以TotalSizeSize任何条发生更改时触发属性更改事件。当然,如果添加/删除条也需要完成。)

于 2013-09-02T18:52:16.843 回答