简体   繁体   English

在WPF中动态绑定触发值

[英]Binding the Trigger value dynamic in WPF

I'm using ListView along with the GridView for displaying the data in tabular format: 我正在使用ListViewGridView以表格格式显示数据:

<ListView>
 <ListView.View>
   <GridView>
     <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
     <GridViewColumn Header="Risk" Width="150" DisplayMemberBinding="{Binding RiskName}" />
   </GridView>
</ListView.View>

I have to change the background color based on the RiskName . 我必须根据RiskName更改背景颜色。 For example, if RiskName is "High" then the background would be Red, if RiskName is "Medium" then the background would be "Yellow", and so on. 例如,如果RiskName为“高”,则背景为红色,如果RiskName为“中”,则背景为“黄色”,依此类推。

I added the style along with trigger to set background based on the value, 我添加了样式和触发器以根据值设置背景,

<Trigger Property="Text" Value="High">
  <Setter Property="Background" Value="Red"/>
</Trigger>
<Trigger Property="Text" Value="Medium">
  <Setter Property="Background" Value="Yellow"/>
</Trigger>

It works fine, but in my case the text of the RiskName is not constant. 它工作正常,但是在我的情况下, RiskName的文本不是恒定的。 The value comes dynamically. 该值是动态产生的。 In WPF is there any way I can set the Value of trigger property dynamically which look something like this? 在WPF中,有什么方法可以动态设置触发器属性的值,如下所示?

<Trigger Property="Text" Value="{Binding RiskName}">
    <Setter Property="Background" Value="{Binding RiskBrush}"/>
</Trigger>

Any suggestion? 有什么建议吗? If not then what is the other work around? 如果没有,那么其他解决方案是什么?

Use a Converter instead of a Trigger . 使用Converter而不是Trigger Bind the Background to RiskName and write a converter that returns a Brush determined by the value of RiskName . Background绑定到RiskName并编写一个转换器,该转换器返回由RiskName的值确定的Brush

Link to MSDN for the interface you need to use IValueConverter - http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter%28v=vs.110%29.aspx 链接到MSDN,以获取需要使用IValueConverter的接口IValueConverter : //msdn.microsoft.com/zh-cn/library/system.windows.data.ivalueconverter%28v=vs.110%29.aspx

A link to a good tutorial on Converters: http://wpftutorial.net/ValueConverters.html 指向有关转换器的良好教程的链接: http : //wpftutorial.net/ValueConverters.html

Something like this? 像这样吗

<converters:MyBrushLookupConverter x:Key="brushLookup" BrushDictionary="{Binding KeyedBrushes}" />

where MyBrushLookupConverter looks like MyBrushLookupConverter的外观

public class MyBrushLookupConverter : DependencyObject, IValueConverter
{
   // This is a dependency property - dependency property gumf omitted for brevity
   public Dictionary<string, Brush> BrushDictionary {get; set;}

   // Convert method
   public Convert(object value, ...)
   {
      return BrushDictionary[(string)value];
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM