Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 976
Peter Lillevold Avatar asked Nov 02 '09 10:11

Peter Lillevold


1 Answers

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.

like image 137
Kent Boogaart Avatar answered Nov 10 '22 15:11

Kent Boogaart