我已经检查了Stack上的现有答案,但仍然无法正确答案:
在我的观点中:
<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" />
在我的视图模型中:
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;
}
}
}
}
属性更改事件正确触发并获取值,正确更新Questions.NumberOfYears但更改从未传播回视图。
答案 0 :(得分:2)
您的OnPropertyChanged
方法未提升PropertyChanged
事件......
像这样更新你的方法:
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
switch (name)
{
case "YearsToSave":
Questions.NumberOfYears = YearsToSave;
handler(this, new PropertyChangedEventArgs(name));
break;
}
}
}
答案 1 :(得分:2)
另一种选择是使用 NotifyPropertyWeaver 项目!
我喜欢它,因为它会自动为您调用Event! (有点黑魔法但方便)