[英]Updating a control after INotifyPropertyChanged
I've checked the existing answers on Stack and still can't get this correct: 我已经检查了Stack上的现有答案,但仍然无法正确:
In my View: 在我看来:
<TextBlock Margin="8,0,0,0"
FontSize="48"
Text="{Binding YearsToSave}"
d:LayoutOverrides="Width">
...
<SurfaceControls:SurfaceSlider x:Name="slider" Grid.Row="8"
Grid.Column="2"
VerticalAlignment="Bottom"
Maximum="{Binding YearsToSaveMaxValue}"
Minimum="{Binding YearsToSaveMinValue}"
Value="{Binding YearsToSave}"
d:LayoutOverrides="Width" />
In my view model: 在我的视图模型中:
class YearsToSaveViewModel : INotifyPropertyChanged
{
private int yearsToSave;
public event PropertyChangedEventHandler PropertyChanged;
public YearsToSaveViewModel()
{
Questions = new SavingsCalculatorQuestions();
YearsToSave = 5; //Binds correctly
YearsToSaveMinValue = 0;
YearsToSaveMaxValue = 30;
}
public SavingsCalculatorQuestions Questions { get; set; }
public int YearsToSaveMinValue { get; private set; }
public int YearsToSaveMaxValue { get; private set; }
public int YearsToSave
{
get { return yearsToSave; }
set
{
yearsToSave = value;
OnPropertyChanged("YearsToSave");
}
}
public void Reset()
{
YearsToSave = 0;
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
switch (name)
{
case "YearsToSave":
Questions.NumberOfYears = YearsToSave;
break;
}
}
}
}
The property changed event fires correctly and gets the value, updates the Questions.NumberOfYears correctly but the change never propagates back to the view. 属性更改事件正确触发并获取值,正确更新Questions.NumberOfYears但更改从未传播回视图。
Your OnPropertyChanged
method is not raising the PropertyChanged
event... 你的
OnPropertyChanged
方法没有引发PropertyChanged
事件......
Update your method like so: 像这样更新你的方法:
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
switch (name)
{
case "YearsToSave":
Questions.NumberOfYears = YearsToSave;
handler(this, new PropertyChangedEventArgs(name));
break;
}
}
}
Another option is using the NotifyPropertyWeaver Project! 另一个选择是使用NotifyPropertyWeaver项目!
I like it,because it automatically does the Event call for you! 我喜欢它,因为它会自动为你做事件! (a bit of black magic but convenient)
(有点黑魔法但方便)
See http://crosscuttingconcerns.com/NotifyPropertyWeaver 请参阅http://crosscuttingconcerns.com/NotifyPropertyWeaver
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.