0

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.

Julia Meshcheryakova
  • 3,162
  • 3
  • 22
  • 42
Akiner Alkan
  • 6,145
  • 3
  • 32
  • 68
  • You can omit TargetName. No target means self. – Leonid Malyshev Nov 09 '16 at 13:29
  • When i omit TargetName, then i get compile error. It says that could not find the template property 'IsExpanded' – Akiner Alkan Nov 09 '16 at 13:32
  • Trigger is for one thing, while `Expander` is another. They are not in *easy-to-use* relations (it's not `Self` or `RelativeSource`). And it's totally ok to use name to reference element. What is the problem to have name? – Sinatr Nov 09 '16 at 13:40
  • So, after I saw this topic http://stackoverflow.com/questions/18403929/setting-isexpanded-on-a-wpf-treeviewitem-from-a-datatrigger, I realized that Triggers are not good for what you want, and you will have to use a converter. – Lupu Silviu Nov 09 '16 at 13:40

1 Answers1

1

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.

Grx70
  • 10,041
  • 1
  • 40
  • 55