I am trying to set expander IsExpanded property inside DataTrigger with Setter.
<ItemsControl.ItemTemplate>
<DataTemplate>
<Expander x:Name="myExpander" />
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding ElementName=myExpander, Path=IsKeyboardFocusWithin}" Value="False">
<Setter TargetName="Self" Property="IsExpanded" Value="False" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
The problem is when I write the code like
TargetName="myExpander"
I wanted some keyword like "self" or "." - something that associates the Setter target with its parent's elements and finds it.
I think what you're looking for is this:
<ItemsControl.ItemTemplate>
<DataTemplate>
<Expander x:Name="myExpander" />
<DataTemplate.Triggers>
<Trigger SourceName="myExpander" Property="IsKeyboardFocusWithin" Value="False">
<Setter TargetName="myExpander" Property="IsExpanded" Value="False" />
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
Note that I used Trigger
with SourceName
rather than DataTrigger
(although the latter would also work). As for the Setter
, you need to set the TargetName="myExpander"
in order to set the property of your expander - if you did not specify the TargetName
, the setter would attempt to set the property on the DataTemplate
itself.
At least that's the theoretical solution. In practice it will not work (or at least not as you expect), because a trigger based on the IsKeyboardFocusWithin
is not a good choice for what I think you're trying to achieve. Better choice would be to subscribe to the LostFocus
event.