isselected on second listview same as on the first
-
16-12-2019 - |
Domanda
I got a grid with 2 listviews in it. The listviews are the same(Only itemsource is different for other items ofc) the datatemplate = Stackpanel that has 1 Label and an other grid. Now I want the grid (inside the stackpanel that is inside the Datatemplate) ONLY to be visible if the item is selected(The Label). I tried it with this code(that I put in the datatemplate of the Listview :
<StackPanel>
<Label content={binding blabla} />
<Grid Visibility="{Binding IsSelected,RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}, Mode=FindAncestor}, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}" >
...random labels etc...
</Gird>
</StackPanel>
This works! HOWEVER if I select an item in the 2nd listview (And only the 2nd) then the first one also shows that grid(on the same "item level").(So for example on the 2nd listview I select the 3th item(the label), then the Grid is show on the 3th item of the 2nd listview but the 3th item grid is show on the first listview!!!!)
I Think this has to do with the relative source thing, but I coudn t find an answer. Hope you guys can help me out.
Soluzione
Just because a ListBox
doesn't have focus, doesn't mean an item gets unselected, and I suspect you have the SelectedItem
or SelectedIndex
bound to the same property in both ListViews
which is making the ListViewItem.IsSelected
synchronized between the two ListViews
I'd suggest making your Grid's Visibility condition be based on 2 properties instead of 1: the ListViewItem.IsSelected
is true, AND if the ListViewItem.IsKeyboardFocusWithin
is set to True.
Here's an example using a DataTrigger
<Style TargetType="{x:Type Grid}" x:Key="GridStyle">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Value="True" Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}}" />
<Condition Value="True" Binding="{Binding Path=IsKeyboardFocusWithin, RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}}" />
</MultiDataTrigger.Conditions>
<Setter Property="Visibility" Value="Visible" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
Actually in retrospect, I think IsKeyboardFocusWithin
will set the items as selected, so perhaps you only need to use IsKeyboardFocusWithin
instead of IsSelected