DependencyPropertyChanged回调事件没有被触发

本文关键字:回调 事件 DependencyPropertyChanged | 更新日期: 2023-09-27 17:49:35

我有一个名为MultiChartControlUserControl,它有一个名为MultiChartInputDetails的依赖属性。

 public ChartsData MultiChartInputDetails
    {
        get { return (ChartsData)GetValue(MultiChartInputDetailsProperty); }
        set { SetValue(MultiChartInputDetailsProperty, value); }
    }
    public static readonly DependencyProperty MultiChartInputDetailsProperty =
        DependencyProperty.Register("MultiChartInputDetails", typeof(ChartsData), typeof(MultiChartControl), new UIPropertyMetadata(new PropertyChangedCallback(MultiChartInputDetailsChanged)));

但是下面的回调方法一次都没有被触发:

private static void MultiChartInputDetailsChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
        MultiChartControl chart = d as MultiChartControl;
        if (chart != null)
        {
            if (chart.ChartGrid.Children != null)
                chart.ChartGrid.Children.Clear();                
            chart.InitilizeData();
        }
        MessageBox.Show("MultiChartInputDetailsChanged fired");
    }

和Main主控件:

<multicharting:MultiChartControl x:Uid="multicharting:MultiChartControl_1" 
                                             MultiChartInputDetails="{Binding Path=MultiChartsInputDetails, ElementName=Chart, Converter={StaticResource DebugConverter}}"/>

DependencyPropertyChanged回调事件没有被触发

这是因为DependencyProperty没有被设置为双向绑定。操作步骤如下:

DependencyProperty.Register("MultiChartInputDetails",
    typeof(ChartsData),
    typeof(MultiChartControl),
    new FrameworkPropertyMetadat(default(ChartsData), 
        FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 
        MultiChartInputDetailsChanged)

进一步检查是否有任何绑定错误。如果你不想提供一个默认情况下执行双向绑定的依赖属性,那么你可以这样写:

<multicharting:MultiChartControl x:Uid="multicharting:MultiChartControl_1" 
    MultiChartInputDetails="{Binding Path=MultiChartsInputDetails, 
                                     Mode=TwoWay,
                                     ElementName=Chart,
                                     Converter={StaticResource DebugConverter}}"/>