WPF: databinding to ListView so that listview item's ForeColor reflects bool property value changes
WPF application, .NET 3.5.
I have a ListView control, to which I bind a collection of business classes.
I'd like to bind the ForeColor of items to a bool property of the class (say: MyClass.Active), so that the items are displayed in black when active, in light gray when disabled.
I want listview items to change their color on-the-fly, I mean when I'd change Active value of one of the instances in my databound collection, its respective listview item would change its color automatically.
What do I need to achieve this? I've found numerous tutorials on WPF databinding on the net, some questions on StackOverflow, but not exactly the same thing, and I don't want to start combining my solution out of everything I can put my hands on, by trial and error.
I know about INotifyPropertyChanged (for my business class), IValueConverter (but should I need it for a bool??), DataTrigger etc.
But which pieces of the puzzle do I really need, what is the simpliest way to achiev开发者_开发知识库e my goal?
I would just do it in a style, and apply that style on your List items. Providing that your object implements INotifyPropertyChanged
and the property changed event gets raised when IsActive changes, this will change the foreground to Gray if IsActive = False
<Style x:Key="DisableInactiveTextStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Black" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsActive}" Value="False">
<Setter Property="Foreground" Value="LightGray" />
</DataTrigger>
</Style.Trigger>
</Style>
<TextBlock Style="{StaticResource DisableInactiveTextStyle}" ... />
I would suggest creating an IValueConverter that takes a bool and returns a color. You can then bind the ForeColor to the MyClass.Active property and use the created converter.
精彩评论