簡體   English   中英

在INotifyPropertyChanged之后更新控件

[英]Updating a control after INotifyPropertyChanged

我已經檢查了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但更改從未傳播回視圖。

你的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;
        }
    }
}

另一個選擇是使用NotifyPropertyWeaver項目!

我喜歡它,因為它會自動為你做事件! (有點黑魔法但方便)

請參閱http://crosscuttingconcerns.com/NotifyPropertyWeaver

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM