簡體   English   中英

更新屬性后,如何在代碼隱藏中調用方法?

[英]How do I have a method in code-behind called when a property is updated?

我需要的是能夠在視圖模型的屬性更新時在視圖類的代碼背后執行代碼。 我的理解是,我需要使用依賴項屬性。

我的視圖模型確實實現了INotifyPropertyChanged

這是我的視圖模型中的屬性:

private DisplayPosition statusPosition;
public DisplayPosition StatusPosition
{
    get { return this.statusPosition; }
    set
    {
        this.statusPosition = value;
        this.OnPropertyChanged("StatusPosition");
    }
}

在我看來,這是我的依賴項屬性:

public DisplayPosition StatusPosition
{
    get { return (DisplayPosition)GetValue(StatusPositionProperty); }
    set { SetValue(StatusPositionProperty, value); }
}
public static readonly DependencyProperty StatusPositionProperty =
        DependencyProperty.Register(
        "StatusPosition",
        typeof(DisplayPosition),
        typeof(TranscriptView),
        new PropertyMetadata(DisplayPosition.BottomLeft));

這是我在視圖類中設置綁定的地方( this.DataContextChanged處理程序):

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    Binding myBinding = new Binding("StatusPosition");
    myBinding.Source = this.DataContext;
    myBinding.NotifyOnTargetUpdated = true;
    this.SetBinding(TranscriptView.StatusPositionProperty, myBinding);
}

當我在視圖中將斷點放在屬性的設置器上時,即使在觀看視圖模型中的值更改並引發PropertyChanged事件之后,也從未遇到斷點。 最終,我的目標是能夠在設置器中放入更多代碼。

如果您感到好奇,那么毛茸茸的細節是,我需要基於此值在多個StackPanel之間移動一個TextBlock。 我似乎找不到找到僅XAML的方式。

通常,這些問題是我所錯過的簡單而又不明顯的事情。 不過,我嘗試做的所有事情都無法幫助我解決這個問題。

當我在視圖中將斷點放在屬性的設置器上時,即使在觀看視圖模型中的值更改並引發PropertyChanged事件之后,也從未遇到斷點。 最終,我的目標是能夠在設置器中放入更多代碼。

你做不到 當您使用DependencyProperties時,綁定屬性更改時將永遠不會調用setter。 這樣做的唯一目的是允許您通過代碼設置DP。

相反,您需要向DP上的元數據添加PropertyChangedCallback ,並在其中添加額外的代碼。 當DP值更新時,無論是通過綁定,代碼等,都將調用此方法。

暫無
暫無

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

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