问题
I'm using ListView
along with the GridView
for displaying the data in tabular format:
<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
. 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.
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. The value comes dynamically. In WPF is there any way I can set the Value of trigger property dynamically which look something like this?
<Trigger Property="Text" Value="{Binding RiskName}">
<Setter Property="Background" Value="{Binding RiskBrush}"/>
</Trigger>
Any suggestion? If not then what is the other work around?
回答1:
Something like this?
<converters:MyBrushLookupConverter x:Key="brushLookup" BrushDictionary="{Binding KeyedBrushes}" />
where MyBrushLookupConverter looks like
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];
}
}
回答2:
Use a Converter
instead of a Trigger
. Bind the Background
to RiskName
and write a converter that returns a Brush
determined by the value of RiskName
.
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
A link to a good tutorial on Converters: http://wpftutorial.net/ValueConverters.html
来源:https://stackoverflow.com/questions/27444178/binding-the-trigger-value-dynamic-in-wpf