views:

319

answers:

2

I would like to programmatically change content of button via style change. I created a style, added setter for Button.ContentProperty, set new style to button, but content was not changed.

I know that I can set button content directly, but now I would like to know why this does not work:

Style aStyle = new Style();  
Setter bSetter = new Setter();
bSetter.Property = Button.ContentProperty;
bSetter.Value = "Some Text"; 
aStyle.Setters.Add(bSetter);
aButton.Style = aStyle;

XAML:

<Button x:Name="aButton" Style="{x:Null}" Click="Button_Click" />

I could change appearance of a button this way, but I couldn't change content. Btw, I found example in MCTS book on WPF.

Any idea?

A: 

This code works for me as is. Are you sure you're not changing Content from other place? you can try

var source = DependencyPropertyHelper.GetValueSource(aButton, ContentControl.ContentProperty);

... to figure it out. I prefer to use WPF snoop for this.

repka
You were right. Content was set elsewhere, prior to setting style. I just did not understand why I could not change value by applying style.
zendar
A: 

Well, today I found out that there is order of precedence when setting property values in WPF. There is number of mechanisms for setting property value and property value depends on how it was set, not when it was set.
Setting property value in XAML or through code will always precede values set by Style (and templates and triggers). That is, when property value is set in XAML or through code, it cannot be overridden by setting style.
To be able to change property value with mechanism of lower precedence, value must be cleared with DependencyObject.ClearValue method.

In my code example above there was one other method that set Button.Content property in code, so style could not change it any more. Solution for this is to add ClearValue method:

Style aStyle = new Style();  
Setter bSetter = new Setter();
bSetter.Property = Button.ContentProperty;
bSetter.Value = "Some Text"; 
aStyle.Setters.Add(bSetter);
aButton.ClearValue(ContentProperty); // <<-- Added this line to clear button content 
aButton.Style = aStyle;
zendar