如何在代码中设置属性值

本文关键字:设置 属性 代码 | 更新日期: 2023-09-27 18:03:13

如何在代码中设置样式的属性值?我有一个资源字典,我想改变代码中的一些属性,我该怎么做?

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;
...

我做错了什么?

如何在代码中设置属性值

您还没有解释运行代码时发生了什么(或没有发生什么)。但是,您发布的代码正在创建new Setter(...),但没有显示您正在使用它做什么。您需要将创建的setter添加到样式中以使其生效。

然而,在你引用的样式的Xaml中已经有一个width属性的setter。所以,我怀疑你实际上是想编辑现有的setter而不是创建一个新的。

为什么不在XAML中创建按钮,然后在代码中实现INotifyPropertyChanged -Interface并为"MyWidth"创建属性?它可以像这样:

XAML:

<Button Name="MyButton" Width="{Bindind Path=MyWidth}" />

Viewmodel/后台代码:

// 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;
}

你可以将按钮的宽度属性绑定到这个"MyWidth"属性,它会在每次你在代码中设置"MyWidth"时自动更新。您需要设置属性,而不是私有变量本身。否则它不会触发更新事件,你的按钮也不会改变。