Reputation: 11
how to set property value of a style in code? i have a resourcedictionary and i want change some property in code, how i do?
the wpf code:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style
x:Key="ButtonKeyStyle"
TargetType="{x:Type Button}">
<Setter Property="Width" Value="{Binding MyWidth}"/>
....
the c# code:
Button bt_key = new Button();
bt_key.SetResourceReference(Control.StyleProperty, "ButtonKeyStyle");
var setter = new Setter(Button.WidthProperty, new Binding("MyWidth"));
setter.Value = 100;
...
what i'm doing wrong?
Upvotes: 1
Views: 1362
Reputation: 1002
Why don't you create the button in your XAML, then implement the INotifyPropertyChanged
-Interface and create a property for "MyWidth" within your code? It could look like this:
XAML:
<Button Name="MyButton" Width="{Bindind Path=MyWidth}" />
Viewmodel/Codebehind:
// This is your private variable and its public property
private double _myWidth;
public double MyWidth
{
get { return _myWidth; }
set { SetField(ref _myWidth, value, "MyWidth"); } // You could use "set { _myWidth = value; RaisePropertyChanged("MyWidth"); }", but this is cleaner. See SetField<T>() method below.
}
// Feel free to add as much properties as you need and bind them. Examples:
private double _myHeight;
public double MyHeight
{
get { return _myHeight; }
set { SetField(ref _myHeight, value, "MyHeight"); }
}
private string _myText;
public double MyText
{
get { return _myText; }
set { SetField(ref _myText, value, "MyText"); }
}
// This is the implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(String propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
// Prevents your code from accidentially running into an infinite loop in certain cases
protected bool SetField<T>(ref T field, T value, string propertyName)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
field = value;
RaisePropertyChanged(propertyName);
return true;
}
You can then bind the Width-Property of your button to this "MyWidth"-property and it will update automatically each time you set "MyWidth" in your code. You need to set the property, not the private variable itself. Otherwise it won't fire its update event and your button won't change.
Upvotes: 0
Reputation: 34218
You haven't explained what is (or isn't) happening when you run your code. However, the code you've posted is creating a new Setter(...)
but doesn't then show what you're doing with it. You would need to add your created setter to the style for it to take any effect.
However, there is already a setter for the width property in the Xaml of the style you're referencing. So, I suspect you actually want to edit the existing setter rather than creating a new one.
Upvotes: 1