WPF:为什么绑定模式OneWay没有调用回调函数?

问题描述 投票:0回答:1

我创建了一个具有一些属性的自定义控件,所有这些似乎都正常工作。

但是经过一些测试,我发现了一个我不明白的奇怪行为。当我以

OneWay
模式绑定属性时,不会调用属性的回调...至少属性没有更新。

我的财产定义如下:

public uint ActiveLeds
{
   get { return (uint)GetValue(ActiveLedsProperty); }
   set { SetValue(ActiveLedsProperty, value); }
}

public static readonly DependencyProperty ActiveLedsProperty =
   DependencyProperty.Register(
       nameof(ActiveLeds),
       typeof(uint),
       typeof(LedControl),
       new FrameworkPropertyMetadata
       {
           DefaultValue = 0u,
           PropertyChangedCallback = new PropertyChangedCallback(ActiveLedsChanged),
           DefaultUpdateSourceTrigger = System.Windows.Data.UpdateSourceTrigger.PropertyChanged,
           BindsTwoWayByDefault = true
       });
private static void ActiveLedsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
   var c = d as LedControl;
   c.ActiveLeds = (uint)e.NewValue;
   c.UpdateLeds();
}

绑定也很常见,并且有效:

<local:LedControl  ActiveLeds="{Binding LedsOn}" />

但是,如果我将绑定更改为 OneWay,则不再调用自定义控件中的回调函数

ActiveLedsChanged

<local:LedControl  ActiveLeds="{Binding LedsOn, Mode=OneWay}" />

这是正常现象还是我做错了什么?

注意

LedsOn
是实现
INotifyPropertyChanged
接口的类的属性。

wpf binding notifications custom-controls
1个回答
0
投票

当您将新的所谓“本地值”分配给当前单向绑定的依赖项属性时,绑定将被删除。 您正在 PropertyChangedCallback 中执行此操作:

private static void ActiveLedsChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var c = d as LedControl; c.ActiveLeds = (uint)e.NewValue; // here c.UpdateLeds(); }

分配是多余的,因为属性已经具有分配的值。更改回调,如下所示。另请注意,您应该使用显式强制转换而不是 
as

运算符。使用

as
时,必须检查结果是否为 null。
private static void ActiveLedsChanged(
    DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    ((LedControl)d).UpdateLeds();
}

© www.soinside.com 2019 - 2024. All rights reserved.