gpt4 book ai didi

wpf - 依赖属性的 PropertyChangedCallback 没有被调用

转载 作者:行者123 更新时间:2023-12-04 14:31:29 26 4
gpt4 key购买 nike

如果有自己的用户控件,带有 DependencyProperty 和相应的回调方法,如下所示:

public partial class PieChart : UserControl
{
public static readonly DependencyProperty RatesProperty = DependencyProperty.Register("Rates", typeof(ObservableCollection<double>), typeof(PieChart),
new PropertyMetadata(new ObservableCollection<double>() { 1.0, 1.0 }, new PropertyChangedCallback(OnRatesChanged)));

[...]

public static void OnRatesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((PieChart)d).drawChart();
}

使用此用户控件时,我将名为“Rates”的 ObservableCollection 绑定(bind)到 RatesProperty。费率和相关方法如下所示:

private ObservableCollection<double> rates;
public ObservableCollection<double> Rates
{
get { return this.rates; }
set
{
if (this.rates != value)
{
this.rates = value;
OnPropertyChanged("Rates");
}
}
}

public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

当我更改 ObservableCollection Rates(例如使用 this.Rates = new ObservableCollection<double>() { 1.0, 2.0 } )时,将按预期调用用户控件的 OnRatesChanged() 方法。但是当我执行以下命令时,它不会被调用:

this.Rates[0] = (double)1;
this.Rates[1] = (double)2;
OnPropertyChanged("Rates");

我预计当我使用正确的属性名称引发 PropertyChanged 事件时,始终会调用用户控件中的相应回调。那是错的吗?我找到了这个线程:Getting PropertyChangedCallback of a dependency property always - Silverlight它涵盖了 silverlight,但我认为在 WPF 中也是如此。

因此,框架在后台检查绑定(bind)属性(在我的示例中为“Rates”)是否发生变化,并且仅当它发生变化时,它才会调用关联的回调,对吗?因此更改我的集合的元素没有效果,我总是必须更改整个集合?

谢谢!

最佳答案

您的结论是正确的,您的 OnRatesChanged 回调只会在 Rates 依赖属性设置为新集合(或 null)时被调用。

为了获得有关集合更改的通知,您还必须注册 NotifyCollectionChangedEventHandler :

private static void OnRatesChanged(
DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var pieChart = (PieChart)d;
var oldRates = e.OldValue as INotifyCollectionChanged;
var newRates = e.NewValue as INotifyCollectionChanged;

if (oldRates != null)
{
oldRates.CollectionChanged -= pieChart.OnRatesCollectionChanged;
}

if (newRates != null)
{
newRates.CollectionChanged += pieChart.OnRatesCollectionChanged;
}

pieChart.drawChart();
}

private void OnRatesCollectionChanged(
object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
...
}

drawChart();
}

关于wpf - 依赖属性的 PropertyChangedCallback 没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12745060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com