UWP用户控件:绑定依赖项属性的集合更改事件
本文关键字:集合 事件 属性 控件 用户 绑定 依赖 UWP | 更新日期: 2023-09-27 18:12:01
当我调用Generate()
时,与ObservableCollection (X
)相关的事件没有被触发。
我做错了什么?
代码:
MyControl.xaml.cs
public ObservableCollection<double> X
{
get { return (ObservableCollection<double>)GetValue(XProperty); }
set { SetValue(XProperty, value); }
}
public static readonly DependencyProperty XProperty =
DependencyProperty.Register(
"X", typeof(ObservableCollection<double>),
typeof(MyControl),
new PropertyMetadata(
new ObservableCollection<double>(),
new PropertyChangedCallback(OnXChanged)));
private static void OnXChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var control = sender as MyControl;
// DoSomething
}
使用MyControl:
的XAML随机页面
<local:MyControl
Title="Test"
X="{Binding TestX, Mode=TwoWay}"
/>
那页是。cs
public sealed partial class MainPage : Page
{
public ObservableCollection<double> TestX { get; set; }
private static Random rand_ = new Random();
public MainPage()
{
this.InitializeComponent();
TestX = new ObservableCollection<double>();
}
private void Generate()
{
TestX.Clear();
for (int i = 0; i < 100; ++i)
{
TestX.Add(rand_.Next(1, 100));
}
}
....
}
请注意,我在输出窗口中没有看到任何BindingExpression错误。
我注意到,如果在页面中这样做,它会工作:
TestX = new ObservableCollection<double>();
this.MyUserControlInstance.X = TestX;
你错过了两件事:
:
确保在构造函数中设置了DataContext
:
public MainPage()
{
this.InitializeComponent();
DataContext = this; // Important, but you should use a seperated ViewModel instead
TestX = new ObservableCollection<double>();
}
第二:
您的类缺少INotifyPropertyChanged
实现,以及TestX
属性的PropertyChanged
调用:
private ObservableCollection<double> _testX;
public ObservableCollection<double> TestX
{
get { return _testX; }
set
{
if (value == _testX) return;
_testX = value;
OnPropertyChanged();
}
}
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
旁注:做MVVM!