How can you programmatically access triggers applied via a DataTemplate?
First, let me start by saying this question is to help us understand the
framework and what it's doing internally, and as such, the associated code
is strictly to demonstrate the question itself and does not represent our
actual code in any way. It is, as they say, for illustrative purposes
only. (Just trying to avoid the inevitable 'I don't understand what'
you're trying to do' or the 'That's not how I would do it' responses.
Again, it's just to support the question. Hope that makes sense.)
That said, consider this XAML defining a String's DataTemplate with two
triggers (each targeting a different element)...
xmlns:system="clr-namespace:System;assembly=mscorlib"
...
<DataTemplate DataType="{x:Type system:String}">
<Border x:Name="Bd" Background="Yellow">
<TextBlock x:Name="Tb" Text="{Binding StringFormat='Formatted
Value: {0}'}" />
</Border>
<DataTemplate.Triggers>
<Trigger SourceName="Bd" Property="IsMouseOver" Value="True">
<Setter TargetName="Bd" Property="Background" Value="Red" />
</Trigger>
<Trigger SourceName="Tb" Property="IsMouseOver" Value="True">
<Setter TargetName="Tb" Property="Foreground" Value="Yellow" />
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
Then in another location in XAML where that template is in scope, we have
this...
<ContentPresenter x:Name="TestPresenter" Content="This is a Test" />
...which works as expected. In code, we can gain access to the root
element of the expanded template (the Border) like this...
var rootElementOfTemplate = VisualTreeHelper.GetChild(TestPresenter, 0) as
FrameworkElement;
...but how and where are the triggers applied? Both
rootElementOfTemplate.Triggers.Count and TestPresenter.Triggers.Count
return zero. What are they set on? Is it even possible to gain
programmatic access to them?
No comments:
Post a Comment