Get DynamicResource Binding in WPF

4.9k Views Asked by At

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.


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.

3

There are 3 best solutions below

1
On

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");
0
On

You can use this:

YourControl.Style = this.FindResource(NameOfYourStyleForThisControl) as Style;
0
On

You can override ColorA inside it's parent by doing this

<TextBlock.Resources>
    <Background x:Key="ColorA">your color</Background >
<TextBlock.Resources>