![](/img/trans.png)
[英]UWP : Binding an observable collection from a dependency property in a user control
[英]UWP User control: collection changed event of a binded dependency property
當我調用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!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.