Yogi_Bear
Yogi_Bear

Reputation: 594

WPF ListView proprties disable line and change color

public class Foo
{
    public string Name { get; set; }
    public bool IsValid{ get; set; }
}

List<Foo> myFoos = new List<Foo>()
{
    new Foo() { Name = "one", IsValid = true },
    new Foo() { Name = "Two", IsValid = false },
    new Foo() { Name = "Three", IsValid = true }
};

lvFoos.Items.Add(myFoos);

<ListView x:Name="lvFoos" SelectionChanged="ListView_SelectionChanged">
    <ListView.View >
        <GridView>
            <GridViewColumn/>
        </GridView>
    </ListView.View>
</ListView>

Hi I have a list of foos and I would like to add them all to my listview in my WPF project. if my foo is not valid, I would like to disable the option to choose him, yet possible to make other foos selectable. I would also want to make the option clear to the user this foo is invalid, maybe make the text red or something. How do I do that? even though its very basic stuff, didn't find simple instructions on the web.

Upvotes: 0

Views: 36

Answers (1)

BionicCode
BionicCode

Reputation: 28968

You do this by creating a Style that targets ListBoxItem and assign it to the ListView.ItemContainerStyle property. Use triggers to change appearance based on conditions:

<ListView>
  <ListView.View>
    <GridView>
      <GridViewColumn Header="Name" 
                      DisplayMemberBinding="{Binding Name}"/>
    </GridView>
  </ListView.View>

  <ListView.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
      <Style.Triggers>
        <DataTrigger Binding="{Binding IsValid}"
                     Value="False">
          <Setter Property="IsEnabled"
                  Value="False" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </ListView.ItemContainerStyle>
</ListView>

By default disabled items (or controls in general) appear grey and are not selectable/hit test visible. So there already is a visual feedback. If you want to change the color of disabled items from grey to e.g. red you would have to override the default ListBoxItem.Template too. Same is if you want to change the highlight color or background of the items.

Upvotes: 1

Related Questions