[英]Data binding failing when trying to bind from MainWindow code-behind to UserControl code-behind
我的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
一个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属性?
在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
上失败。 由于目前未知的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.