绑定到自定义MVVM控件

时间:2014-12-16 23:51:52

标签: c# mvvm binding windows-phone-8.1 inotifypropertychanged

我有自定义用户控件,它使用MVVM:INotifyPropertyChanged。我的应用程序也使用MVVM和INotifyPropertyChanged,但当我尝试将值绑定到自定义用户控件时,应用程序失败。

"例外无法分配到属性'%0'。"

我需要使用TwoWay绑定。谢谢你的帮助。

自定义用户控制

    private double _value = 0;
    public double Value
    {
        get
        {
            return _value;
        }
        set
        {
            _value = value;
            RaisePropertyChanged("Value");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

绑定到元素:

    private double _startMinutes;
    public double StartMinutes
    {
        get
        {
            return _startMinutes;
        }
        set
        {
            _startMinutes = value;
            RaisePropertyChanged("StartMinutes");
        }
    }

    <controls:RadialSlider
        Value="{Binding StartMinutes}"
    />

1 个答案:

答案 0 :(得分:2)

您不能只绑定到普通属性。

绑定是通过DependencyProperty完成的。最简单的方法是通过propdp代码段。他们看起来像:

    public double Value
    {
        get { return (double)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Value.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(double), typeof(RadialSlider), new PropertyMetadata(0));

现在您的绑定将按预期工作。有关详情,请参阅MSDN