为什么不在 XAML 中创建按钮,然后INotifyPropertyChanged
在代码中实现 -Interface 并为“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;
}
然后,您可以将按钮的宽度属性绑定到此“MyWidth”属性,每次您在代码中设置“MyWidth”时它都会自动更新。您需要设置属性,而不是私有变量本身。否则它不会触发它的更新事件,你的按钮也不会改变。