【问题标题】:How do I have a method in code-behind called when a property is updated?更新属性时如何在代码隐藏中调用方法?
【发布时间】:2011-07-09 03:05:46
【问题描述】:

当我的视图模型上的属性更新时,我需要能够在我的视图类的代码隐藏中执行代码。我的理解是我需要使用依赖属性。

我的视图模型确实实现了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 事件之后,它也不会被击中。最终,我的目标是能够在 setter 中放入更多代码。

如果你好奇的话,毛茸茸的细节是我需要根据这个值在多个 StackPanel 之间移动一个 TextBlock。我似乎无法找到一种仅限 XAML 的方法。

通常情况下,这些问题都是我错过的简单小事。不过,我所做的一切都无法帮助我解决这个问题。

【问题讨论】:

    标签: c# wpf xaml binding dependency-properties


    【解决方案1】:

    当我在视图中的属性设置器上设置断点时,即使在我观察视图模型中的值更改并且引发 PropertyChanged 事件之后,它也不会被击中。最终,我的目标是能够在 setter 中放入更多代码。

    你不能这样做。当您使用 DependencyProperties 时,绑定属性更改时永远不会调用 setter。它的唯一目的是允许您从代码中设置 DP。

    您需要将PropertyChangedCallback 添加到您的 DP 的元数据中,并在那里添加额外的代码。这将在 DP 值更新时调用,无论是通过绑定、代码等方式。

    【讨论】:

    • 非常感谢!这正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 2012-09-27
    相关资源
    最近更新 更多