Switch to fluid Switch to wfix Switch to fixed

StackPanel

dynamic rants = new Stack();

Often times I’ve come across a scenario where I need to access a control in the codebehind, for setting a property or making a change, when the control/rule/resource is inside a DataTemplate which is then inside a ResouceDictionary.

In this case, the control is not directly available to codebehind byName, because it’s part of the Resources of the page/window/usercontrol.

To gain access, first define a key on top inside the ResourceDictionary or

<Window.Resources>

<FieldValidationRule x:Key=”FieldRuleKey”/>

Here goes DataTemplate…

Inside DataTemplate somewhere inside a control goes the actual validation rule…

<TextBox>
<TextBox.Text>
<Binding Path=”Value”>
<Binding.ValidationRules>
<StaticResource ResourceKey=”FieldRuleKey”/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>

</Window.Resources>

Now in the codebehind,

FieldValidationRule fieldRule = Resources["FieldRuleKey"] as FieldValidationRule;

Now you can play with fieldRule like, assign a value to it’s property