我有一个 WPF 样式,我将其应用于列表框项目。目前,每个项目都绑定(bind)到一个 KeyValuePair。我在 ListBoxItem 内的 TextBlock 中显示键:
<TextBlock Name="Label" Text="{Binding Key}" />
我想要做的是使 Style 通用,这样如果数据不是 KeyValuePair(可能只是一个字符串),我可以将数据正确绑定(bind)到 TextBlock。
有没有办法将参数传递给样式或数据模板或使数据绑定(bind)通用?
我的风格:
<Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="Border" Padding="2" SnapsToDevicePixels="true" CornerRadius="4" BorderThickness="1">
<TextBlock Name="Label" Text="{Binding Key}" />
</Border>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="True"/>
</MultiTrigger.Conditions>
<Setter TargetName="Border" Property="Background" Value="{StaticResource SelectionGradient}" />
</MultiTrigger>
<ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
最佳答案
让我给你举一个简单的例子。假设您的 TextBox
包含一个数字,如果该数字为负数,您希望它具有红色背景,或者如果 >= 0
这是您要编写的样式:
<TextBlock Text="{Binding Key}" >
<TextBlock.Style>
<Style TargetType="TextBox">
<Setter Property="Background" Value="{Binding Key, Converter={StaticResource MyConverterResource}" />
</Style>
</TextBlock.Style>
</TextBlock>
这是您要编写的转换器:
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double source = (double)value;
return source < 0 ? Brushes.Red : Brushes.Green;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// We don't care about this one here
throw new NotImplementedException();
}
}
并且,要访问 xaml 中的转换器,您只需执行以下操作,假设您的转换器位于命名空间 MyNamespace
中:
<Window xmlns:my="clr-namespace:MyNamespace">
<Window.Resources>
<my:MyConverter x:Key="MyConverterResource">
</Window.Resources?
<!-- Your XAML here -->
</Window>
(当然,您可以将其放入任何Resources
中,可能是UserControl
或其他)
这将允许您通过编写 {StaticResource MyConverterResource}
在这里,您将有一个条件样式,转换器根据一个参数决定将哪种颜色设置为背景,在我的例子中,是值本身(但它可以是您想要的任何颜色)
关于c# - 是否可以将参数(绑定(bind))传递给 WPF 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12464589/