双向绑定到用户控件中的依赖项属性并调用方法

时间:2015-12-22 21:37:29

标签: c# wpf xaml mvvm binding

我知道,标题有点令人困惑所以让我解释一下。我有一个具有依赖项属性的用户控件。我使用名为Input的常规属性访问此依赖项属性。在我的视图模型中,我还有一个名为Input的属性。我在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 = value;遗漏,那么我会收到编译错误。

我需要这样的东西:

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

如果我在视图模型中创建Input属性,请执行以下操作:

public string Input
        {
            get; set;
        }

然后它工作,但是,当我更改属性时,我无法调用我需要调用的InputChanged()方法。所有建议都表示赞赏。

1 个答案:

答案 0 :(得分:1)

INotifyPropertyChanged

中实施ViewModel
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));
        }
    }

}

在您的情况下,您可以在usercontrol背后的代码中执行此操作