尝试从MainWindow代码隐藏绑定到UserControl代码隐藏时,数据绑定失败

时间:2015-10-02 15:15:27

标签: c# wpf xaml data-binding user-controls

我的MainWindow使用INotifyPropertyChanged接口。我正在使用OnPropertyChanged功能,我已经使用了一段时间,这是有效的 在我的MainWindow代码隐藏中,我有这个:

public ObservableCollection<bool> MwOc { get; set; }

private bool _mwBool;
public bool MwBool { get { return _mwBool; } set { _mwBool = value; OnPropertyChanged(); } }

public MainWindow()
{
    InitializeComponent();

    MwOc = new ObservableCollection<bool>();

    MwOc.Add(false);
    MwBool = true;

    Console.WriteLine("MwOc:   " + MwOc.Count);
    Console.WriteLine("MwBool: " + MwBool);

    DataContext = this;
}

我所有的MainWindow xaml都是这样的:

<local:UserControl1 x:Name="Control" UcOc="{Binding MwOc}" UcBool="{Binding MwBool}" />

我的UserControl有两个依赖项属性:UcOc ObservableCollection<bool>UcBool a bool
这是我的UserControl代码:

public ObservableCollection<bool> UcOc
{
    get { return (ObservableCollection<bool>)GetValue(UcOcProperty); }
    set { SetValue(UcOcProperty, value); }
}

public static readonly DependencyProperty UcOcProperty =
DependencyProperty.Register("UcOc", typeof(ObservableCollection<bool>), typeof(UserControl1));

public bool UcBool
{
    get { return (bool)GetValue(UcBoolProperty); }
    set { SetValue(UcBoolProperty, value); }
}

public static readonly DependencyProperty UcBoolProperty =
    DependencyProperty.Register("UcBool", typeof(bool), typeof(UserControl1));

public UserControl1()
{
    InitializeComponent();
    UcOc = UcOc ?? new ObservableCollection<bool>();

    DataContextChanged += (o, e) => { Console.WriteLine("DataContextChanged"); Print(); };
}

public void Print()
{
    UcOc = UcOc ?? new ObservableCollection<bool>();
    Console.WriteLine("UcOc:   " + UcOc.Count);
    Console.WriteLine("UcBool: " + UcBool);
}

我的UserControl xaml为空(只有默认的<Grid></Grid>

该程序的输出是

MwOc:   1
MwBool: True
DataContextChanged
UcOc:   0
UcBool: False

当DataContext更改时,我应该如何更新UserControl属性?

1 个答案:

答案 0 :(得分:1)

在MainWindow xaml中,绑定需要将NotifyOnTargetUpdated属性设置为true 而不是:

<local:UserControl1 x:Name="Control" UcOc="{Binding MwOc}" UcBool="{Binding MwBool}" />

使用:

<local:UserControl1 x:Name="Control" UcOc="{Binding MwOc, NotifyOnTargetUpdated=true}" UcBool="{Binding MwBool, NotifyOnTargetUpdated=true}" />

在UserControl中,订阅DataContextChanged事件也会导致绑定在ObservableCollection<bool>而不是bool上失败。目前未知的原因。