将自定义userControl属性与DependencyProperty绑定

时间:2020-10-27 11:05:26

标签: c# wpf binding dependency-properties

我正在尝试使用DependencyProperty绑定自定义UserControl属性。

这是我的userControl,值是我要绑定的属性:

public partial class MyCustomUserControl: UserControl
{
    bool _value = false;
    public bool Value
    {
        get
        {
            return _value;
        }
        set
        {
            SetState(value);
        }
    
    public static DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(bool), typeof(MyCustomUserControl));

}

在这里,我们有了带有InotifyPropertyChanged和公共属性CustomViewModelValueProperty的viewModel:

public class CustomViewModel: INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged == null) { return; }
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    protected void SetField<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return;
        field = value;
        OnPropertyChanged(propertyName);
    }


    private bool _viewModelValue;
    public bool CustomViewModelValueProperty
    {
        get { return _viewModelValue; }
        set { SetField(ref _viewModelValue, value,nameof(CustomViewModelValueProperty)); }
    }

查看构造函数:

CustomViewModel customViewModel= new CustomViewModel();
Forms.CustomWindow customWindow = new CustomWindow ()
{
   DataContext = customViewModel,
};

包含MyCustomUserControl和绑定的XAML:

<CustomWindow:MyCustomUserControl x:Name="UserControl1" HorizontalAlignment="Left" VerticalAlignment="Top" Height="48" Width="48" Value="{Binding Path=CustomViewModelValueProperty, Mode=OneWay}"/>

在这一点上,当我强制PropertyChanged时,它具有一个订阅,但是没有调用MyCustomUserControl中的“值”设置器,我缺少什么?。

谢谢!

0 个答案:

没有答案
相关问题