两种方式绑定到用户控件中的依赖项 属性 并调用方法

Two Way binding to a Dependency Property in a User Control and call a method

我知道,标题有点混乱所以让我解释一下。我有一个具有依赖项 属性 的用户控件。我使用名为 Input 的常规 属性 访问此依赖项 属性。在我的视图模型中,我还有一个名为 Input 的 属性。我使用 two-way 绑定将这两个属性绑定在 XAML 中,如下所示:

<uc:rdtDisplay x:Name="rdtDisplay" Input="{Binding Input, Mode=TwoWay}" Line1="{Binding myRdt.Line1}" Line2="{Binding myRdt.Line2}" Height="175" Width="99"  Canvas.Left="627" Canvas.Top="10"/>

好的,在我的视图模型中,只要 Input 的值发生变化,我就会调用一个方法,如我的 属性:

所示
public string Input
        {
            get
            {
                return input;
            }
            set
            {
                input = value;
                InputChanged();
            }
        }

问题在于,当我在我的视图模型中设置 Input 的值时,它只会根据 属性 中的 setter 更新变量 input 的值。我怎样才能让它更新回用户控件中的依赖项 属性?如果我将代码 input = value; 留在外面,则会出现编译错误。

我需要这样的东西:

public string Input
            {
                get
                {
                    return UserControl.Input;
                }
                set
                {
                    UserControl.Input = value;
                    InputChanged();
                }
            }

如果我在视图模型中使输入 属性 如下所示:

public string Input
        {
            get; set;
        }

然后它起作用了,但是,我无法调用 属性 更改时需要调用的 InputChanged() 方法。感谢所有建议。

在您的 ViewModel

中实施 INotifyPropertyChanged
public class Sample : INotifyPropertyChanged
{
    private string input = string.Empty;
    public string Input
    {
        get
        {
            return input;
        }
        set
        {
            input = value;
            NotifyPropertyChanged("Input");
            InputChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

}

对于你的情况,你可以在你的用户控件后面的代码中完成