从viewmodel更改wpf样式

时间:2014-04-27 14:39:40

标签: c# wpf mvvm

我有一个DataTemplate:

 <DataTemplate
            DataType="{x:Type local:ConnectionViewModel}"
            >
            <!-- The connection is represented by a curved arrow. -->
            <ca:CurvedArrow

                    StrokeThickness="2"
                    Points="{Binding Points}"
                    Fill="{StaticResource connectionBrush}"
                    Stroke="{StaticResource connectionBrush}"
                />

        </DataTemplate>

这代表了我在视图中的所有连接器。 我想要做的是为viewmodel中的特定特定连接器设置不同的填充和描边。 我该如何实现呢?

1 个答案:

答案 0 :(得分:1)

您应该避免在viewmodel中使用任何UI对象。

对于上述用例,您可以使用转换器并继续在视图模型中仅包含业务对象级别信息。

例如,您的Connection类可以包含enum : ConnectorType {Arrow,Circle,Rectangle}的属性,然后您可以编写Converter,将枚举类型转换为所需的颜色画笔。示例代码如下:

//Inside Resources. local=namespace where you have this converter
   <local:ConnectorType2BrushConverter x:Key="ConnectorType2BrushConverter" />
....
    <ca:CurvedArrow

                        StrokeThickness="2"
                        Points="{Binding Points}"
                        Fill="{Binding Path=ConnectorType, Converter={StaticResource ResourceKey=ConnectorType2BrushConverter}"
                    />

    ....

        public class ConnectorType2BrushConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                var connectorType = (ConnectorType)value;
                if (connectorType == ConnectorType.Arrow)
                {
                    return new SolidColorBrush(Color.FromRgb(1, 1, 1));
                }
                else    .....
            }

            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }