c# - 是否可以将参数(绑定(bind))传递给 WPF 样式

标签 c# wpf xaml styles controltemplate

我有一个 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/

相关文章:

c# - 基于查询参数的 WCF REST 服务 url 路由

c# - ASP.NET 自动注销

当 IsSynchronizedWithCurrentItem=true 时 WPF ListBox 绑定(bind)

c# - 在代码隐藏 WinRT 中更改属性 Canvas.Left 和 Canvas.Top

c# - 尽管存在错误 View ,但找不到错误页面 ASP.NET MVC

c# - WinForms 中多余的滚动条

WPF + MVVM + 休眠 : A simple example?

c# - 如何使我的表单透明,但我在上面绘制的内容却不透明?

xaml - 允许用户在Windows 8应用程序中使用RichEditBox中的选项卡吗?

c# - 为什么我的模板的文本框无法绑定(bind)