【发布时间】:2016-05-15 22:40:18
【问题描述】:
我正在尝试将 List<bool> 从 MainWindow 绑定到我的 UserControl。 MainWindow 从其他 UserControl 获取列表。我想将它绑定到它的子控件并在 List 的元素发生更改时执行一些操作,所以我编写了这段代码:
MainWindow 类:
public static readonly DependencyProperty mRowsInfoProperty =
DependencyProperty.Register("mRowsInfo", typeof(List<bool>), typeof(MainWindow),
new FrameworkPropertyMetadata(new List<bool>()));
public List<bool> mRowsInfo
{
get { return (List<bool>)GetValue(mRowsInfoProperty); }
set { SetValue(mRowsInfoProperty, value); }
}
public List<bool> RowsInfo
{
get { return mRowsInfo; }
set
{
mRowsInfo = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("RowsInfo"));
}
}
MainWindow xaml:
<local:CustomGrid isRowValid="{Binding RowsInfo, Mode=TwoWay}">
<local:ControlButtons ButtonsBacklitList="{Binding mRowsInfo, ElementName=myWindow}"/>
用户控制类:
public static readonly DependencyProperty ButtonsBacklitListProperty =
DependencyProperty.Register("ButtonsBacklitList", typeof(ObservableCollection<bool>), typeof(ControlButtons),
new FrameworkPropertyMetadata(new ObservableCollection<bool>(), onBBLCallBack));
public ObservableCollection<bool> ButtonsBacklitList
{
get { return (ObservableCollection<bool>)GetValue(ButtonsBacklitListProperty); }
set { SetValue(ButtonsBacklitListProperty, value); }
}
private static void onBBLCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
ControlButtons h = sender as ControlButtons;
if (h != null)
{
h.onBBLChanged();
}
}
protected virtual void onBBLChanged()
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("ButtonsBacklitList"));
Console.WriteLine("UPDATED");
}
当我在代码中的某个点中断时(单击按钮后)ButtonsBacklitList 始终为空。我应该更改或添加什么才能正确执行此操作?
【问题讨论】:
-
首先,为什么
INotifyPropertyChanged和DependencyProperty一起使用?将List<bool>实现为DependencyProperty将允许在重新实例化列表(或重新分配给不同引用地址的另一个列表)时触发绑定。