【发布时间】:2015-12-30 20:32:50
【问题描述】:
我的 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
这是我的用户控件代码:
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 属性?
【问题讨论】:
-
编辑代码并添加两个依赖属性以获得更好的帮助...
-
DataContextChanged被触发后,绑定的属性可能尚未更新。您应该改为处理UserControl的事件TargetUpdated。但是不确定为什么要获取DataContextChanged事件处理程序中的值。 -
我只检查了
DataContextChanged事件处理程序,因为我认为这些值会在那时更新。我在UserControl中添加了TargetUpdated事件处理程序,但它从未被触发。 -
看来您需要将 Binding 的
NotifyOnTargetUpdated设置为true。例如:你需要UcOc="{Binding MwOc, NotifyOnTargetUpdated=true}"而不是UcOc="{Binding MwOc}" -
是的。我以这种方式测试 UcOc="{Binding MwOc, NotifyOnTargetUpdated=true}" 触发 TargetUpdated 事件。
标签: c# wpf xaml data-binding user-controls