爲什麼不在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;
}
然後,您可以綁定您的按鈕的寬度屬性這個 「MyWidth」 - 屬性,它每次您在代碼中設置「MyWidth」時都會自動更新。你需要設置屬性,而不是私有變量本身。否則,它不會觸發其更新事件,並且您的按鈕不會更改。
嗯,怎麼了?你目前的執行情況如何,以致你不滿意? – DHN 2013-03-11 09:34:53