Given a styled WPF DependencyObject, how can I get the Style Key in code?
Asked Answered
G

1

6

I have a set of controls bound to data, on which I would like to programmaticaly add validators to the bindings. Currently I'm able to iterate over the visual tree to find those controls with bindings, and also add my validators to these controls. But to further specify which controls should have specific validation I wanted to use styles. So my XAML looks like this:

<TextBox Name="someTextBox" Style="{StaticResource optionalNumericTextBox}" />

Here, the optionalNumericTextBox style serves both adding a validation error template and as a decorator to indicate that this textbox should have the optional numeric validator applied.

The problem occurs when I'm traversing the visual tree, discovers a control with bindings, and then need to determine the style in use. Currently I've tried

dependencyObject.GetValue(FrameworkElement.StyleProperty)

which gives me a Style object but as far as I can tell, this object does not carry the 'optionalNumericTextBox' value. Is it even possible to determine the key or is this information lost in the XAML reader?

Greenlee answered 2/11, 2009 at 10:59 Comment(0)
H
5

When using StaticResourceExtension, this information is lost at compile time when converting your XAML to BAML. Using DynamicResourceExtension, on the other hand, keeps the key around so the resource can be resolved at runtime. To get at the key, you'll need to use ReadLocalValue():

//this gets the Style
var s = textbox.GetValue(TextBox.StyleProperty);
//this gets a ResourceReferenceExpression
var l = textbox.ReadLocalValue(TextBox.StyleProperty);

The problem is, ResourceReferenceExpression is an internal type, so you'll need to use reflection to pull out the key.

As an alternative to all this, have you considered hijacking the Tag property instead?

<Style x:Key="optionalNumericTextBox" TargetType="TextBox">
    <Setter Property="Tag" Value="optionalNumericTextBox"/>
</Style>

Then your code can simply check the Tag property on the TextBox.

Hominy answered 2/11, 2009 at 11:58 Comment(1)
Great tip there, using a property setter. Actually pointed me in the direction of using an attached property instead of the Tag. So now I use something like: <Setter Property="ViewValidator.ValidationStyle" Value="optionalNumeric" /> Works like a charm!Greenlee

© 2022 - 2024 — McMap. All rights reserved.