views:

688

answers:

3

Can any one help me to get DynamicResource Binding in WPF by code?

I have set binding Like follow,

TextBlock Background={DynamicResource ColorA} Name="TB" in Xaml.

and i need to get the - TB's background is binded to "ColorA". how can i access this DynamicResource Binding Expression in WPF by coding. when i try to get TB.Background, it is white(#FFFFF..) or if i already given the value to the Resorce key "ColorA" that will be given. but i want to get this Binding Expression. Thank in advance for your Help.

+1  A: 

You can use the FrameworkElement.SetResourceReference method:

MSDN: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.setresourcereference.aspx

Provided your xaml has this:

<TextBlock x:Name="TB">

You can write this in the code behind:

TB.SetResourceReference(BackgroundProperty, "ColorA");
Yogesh
Ray Burns
A: 

I think my Question wasn't clear. I want to get What Reource Binding was done to the "TB" in Xaml by code. But the aren't any TB.GetResourceReference. I Want some think like that. Where that Binding expression is kept in WPF. I need to get the TB's BackgroundProperty was Binded to Which( answer "ColorA") key? thank a lot for sudden response.

Kuman
+1  A: 

I think the answer posted for this MSDN question will get what you are looking for.

Abe Heidebrecht
That is the one i want. Thanks for your help.
Kuman
Yes but DON'T use the code from the MSDN post as-is: It is much more efficient if you replace the GetLocalValue(b, Button.ContentProperty) with b.ReadLocalValue(Button.ContentProperty) and eliminate the extra method. GetLocalValueEnumerator() is slow.
Ray Burns
It work well. Thanks.
Kuman