如何在代码中设置样式的属性值?我有一个resourcedictionary,我想在代码中更改一些属性,我该怎么做?
wpf代码:
<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}"/>
....
c#代码:
Button bt_key = new Button();
bt_key.SetResourceReference(Control.StyleProperty, "ButtonKeyStyle");
var setter = new Setter(Button.WidthProperty, new Binding("MyWidth"));
setter.Value = 100;
...
我做错了什么?
答案 0 :(得分:1)
您没有解释运行代码时发生了什么(或没有发生)。但是,您发布的代码是创建new Setter(...)
但不会显示您正在使用它执行的操作。您需要将创建的setter添加到样式中才能获得任何效果。
但是,您引用的样式的Xaml中已存在width属性的setter。所以,我怀疑你实际上想要编辑现有的setter而不是创建一个新的setter。
答案 1 :(得分:0)
为什么不在XAML中创建按钮,然后实现INotifyPropertyChanged
- 接口并在代码中为“MyWidth”创建属性?它看起来像这样:
XAML:
<Button Name="MyButton" Width="{Bindind Path=MyWidth}" />
视图模型/代码隐藏:
// 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;
}
然后,您可以将按钮的Width-Property绑定到此“MyWidth”属性,并且每次在代码中设置“MyWidth”时它都会自动更新。您需要设置属性,而不是私有变量本身。否则它不会触发其更新事件,您的按钮也不会改变。