我有3个属性的对象:
CouldBeWhite bool
CouldBeGreen bool
CouldBeRed bool
If CouldBeWhite is true, then foreground of row should be white, if
CouldBeGreen is true, and CouldBeWhite is false, then row should be
Green If CouldBeRed is true, and and CouldBeWhite is false and
CouldBeGreen is false then row should be Red In other case row
should be blue.
我现在的想法是在viewmodel Color处有一些新属性,当我计算行的颜色时。
或者可能有更好的方法来实现它?
答案 0 :(得分:1)
在自定义值转换器中实现此逻辑可能更简洁。类似的东西:
public class RowColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var myObj = value as MyObjectType();
if (myObj.CouldBeWhite)
{
return new SolidColorBrush(Colors.White);
}
if (myObj.CouldBeGreen )
{
return new SolidColorBrush(Colors.Green);
}
if (myObj.CouldBeRed )
{
return new SolidColorBrush(Colors.Red);
}
return new SolidColorBrush(Colors.Blue);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
答案 1 :(得分:1)
将此枚举添加到您的项目中: -
public enum RowState
{
Blue,
Red,
Green,
White
}
然后将此属性添加到ViewModel: -
private RowState _RowState;
public RowState RowState
{
get { return _RowState; }
set
{
if (value != _RowState)
{
_RowState = value;
NotifyPropertyChanged("RowState"); // Assumes typical implementation of INotifyPropertyChanged
}
}
}
private void UpdateRowState()
{
if (CouldBeWhite)
RowState = RowState.White;
else if (CouldBeGreen)
RowState = RowState.Green;
else if (CouldBeRed)
RowState = RowState.Red;
else
RowState = RowState.Blue;
}
每个CouldBeXXX
属性更改时调用UpdateRowState。
考虑到你可能没有把前景变成白色,红色或绿色,只是一时兴起。 为什么它的白色,红色或绿色会有一些原因。因此,在您的代码中,请考虑一个简单的短名称来表示这些原因,并将颜色名称替换为更有意义的名称。
现在,在此blog中获取StringToValueConverter
的代码。在UserControl.Resources
:
<local:StringToObjectConverter x:Key="RowStateToBrush">
<ResourceDictionary>
<SolidColorBrush Color="Red" x:Key="Red" />
<SolidColorBrush Color="Green" x:Key="Green" />
<SolidColorBrush Color="White" x:Key="White" />
<SolidColorBrush Color="Blue" x:Key="__default__" />
</ResourceDictionary>
</local:StringToObjectConverter>
您可以绑定TextBlock
:
<TextBlock Text="{Binding SomeTextProperty}" Foreground="{Binding RowState, Converter={StaticResource RowStateToBrush}}" />