我在2-3个地方有这个代码,并且常见的是除了绑定路径之外的样式“BidMovement”需要在其他地方更改(“AskMovement”,“StaleMovement”)。 这是否可以在WPF中定义样式并在实际使用时更改某些元素(绑定路径)?
<Border Name="BidBorder" Grid.Column="0" Padding="5" Margin="5" CornerRadius="10">
<Border.Style>
<Style TargetType="{x:Type Border}">
<Style.Triggers>
<DataTrigger Binding="{Binding BidMovement}" Value="{x:Static crosses:PriceMovement.Up}">
<Setter Property="Background" Value="Green" />
</DataTrigger>
<DataTrigger Binding="{Binding BidMovement}" Value="{x:Static crosses:PriceMovement.Down}">
<Setter Property="Background" Value="OrangeRed" />
</DataTrigger>
<DataTrigger Binding="{Binding BidMovement}" Value="{x:Static crosses:PriceMovement.Stale}">
<Setter Property="Background" Value="DarkOrange" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
答案 0 :(得分:0)
创建ValueConverter
,将Movements
转换为Brushes
。它看起来像这样:
public class MovementToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var movement = value as Movement;
if (movement == PriceMovement.Up)
return Brushes.Green;
//return values for the other cases accordingly
return Brushes.Transparent; //default
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
要使用它,请将应用程序的命名空间添加到命名空间,并将转换器作为静态资源添加到Windows资源中:
<Window //other attributes omitted for brevity
xmlns:l="clr-namespace:YourApplication">
<Window.Resources>
<l:MovementToBrushConverter x:Key="converter" />
</Window.Resources>
然后在边框上定义绑定并添加值转换器,如下所示:
<Border Background="{Binding BidMovement, Converter={StaticResource converter}}"></Border>