XAML에 단추를 만든 다음 INotifyPropertyChanged
-Interface를 구현하고 코드에서 "MyWidth"속성을 만드는 이유는 무엇입니까? 그것은 다음과 같이 수 :
XAML :
<Button Name="MyButton" Width="{Bindind Path=MyWidth}" />
뷰 모델/Codebehind가 : 그런 다음이 "MyWidth"-property과에 버튼의 폭-속성을 바인딩 할 수 있습니다
// 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"를 설정할 때마다 자동으로 업데이트됩니다. 개인 변수 자체가 아니라 속성을 설정해야합니다. 그렇지 않으면 업데이트 이벤트가 발생하지 않으며 버튼이 변경되지 않습니다.
흠, 무엇이 잘못 되었나요? 현재의 구현은 무엇 때문에 만족스럽지 않은가? WPF 코드 :
DHN