asusralis
Topic Author
Posts: 141
Joined: 30 Jul 2018, 05:03

How to use TargetName in a Setter from a derived style?

24 May 2023, 14:05

I have a style for a ListBoxItem in my resources. In the template I have a control named "border" and a control template trigger that changes the appearance of this control once the ListBoxItem is selected using TargetName.

I have a ListBox that uses needs to change the appearance of this border once a condition is met.
<ListBox.ItemContainerStyle>
 	<Style BasedOn="{StaticResource {x:Type ListBoxItem}}" TargetType="ListBoxItem">
                                    ...
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding IsLocked}" Value="True">
                                            <Setter TargetName="border" Property="Style" Value="{StaticResource Border.Alt.Locked}" />
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
</ListBox.ItemContainerStyle>
However, this doesn't change the 'border' control once IsLocked becomes true. How is it possible to do what I want without recreating the style? Thanks!
 
User avatar
sfernandez
Site Admin
Posts: 2869
Joined: 22 Dec 2011, 19:20

Re: How to use TargetName in a Setter from a derived style?

24 May 2023, 19:42

It is not possible to access template elements from outside the ControlTemplate. So a Style trigger or setter cannot reference any template element.

You need to modify properties in the styled control, that can then be used from inside the template. For example you can have something like this:
<Style BasedOn="{StaticResource {x:Type ListBoxItem}}" TargetType="ListBoxItem">
  ...
  <Style.Triggers>
    <DataTrigger Binding="{Binding IsLocked}" Value="True">
      <Setter Property="Tag" Value="{StaticResource Border.Alt.Locked}" />
    </DataTrigger>
  </Style.Triggers>
</Style>
<ControlTemplate TargetType="ListBoxItem">
  <Border x:Name="border" Style="{TemplateBinding Tag}" .../>
  ...
</ControlTemplate>
 
asusralis
Topic Author
Posts: 141
Joined: 30 Jul 2018, 05:03

Re: How to use TargetName in a Setter from a derived style?

25 May 2023, 14:50

Thanks, it works. Is Tag typically used for something like this? And if I needed multiple properties to modify like this, would I eventually have to create a child class from ListBoxItem?
 
User avatar
sfernandez
Site Admin
Posts: 2869
Joined: 22 Dec 2011, 19:20

Re: How to use TargetName in a Setter from a derived style?

26 May 2023, 13:16

Yeah, the Tag property is used a lot in these situations. Another option is to create extra attached properties that you can use to configure your templates. For example you can have extra properties like Icon, NormalImage, HoverImage, PressImage...

Who is online

Users browsing this forum: asusralis, Bing [Bot] and 1 guest