gpt4 book ai didi

wpf - 依赖属性 - 更新源

转载 作者:行者123 更新时间:2023-12-04 07:43:22 28 4
gpt4 key购买 nike

我对自定义依赖属性感到疯狂。我已经在这里检查了很多线程,但还没有找到任何解决方案。如果源提供特定值(给定示例为 null),我想要做的是替换属性的值。无论我尝试什么,源中的属性值都保持为空并且永远不会更新。

这是我的自定义控件:

public class TextBoxEx : TextBox
{
public TextBoxEx()
{
TrueValue = 0;
this.TextChanged += (s, e) =>
{
TrueValue = Text.Length;
SetCurrentValue(MyPropertyProperty, TrueValue);
var x = BindingOperations.GetBindingExpression(this, MyPropertyProperty);
if (x != null)
{
x.UpdateSource();
}
};
}

public int? TrueValue { get; set; }

public int? MyProperty
{
get { return (int?)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}

public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int?), typeof(TextBoxEx), new PropertyMetadata(null, PropertyChangedCallback));

private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue == null)
{
d.SetCurrentValue(MyPropertyProperty, (d as TextBoxEx).TrueValue);
}
}
}

这是我正在绑定(bind)的 DataContext:
public class VM : INotifyPropertyChanged
{
private int? _Bar = null;

public int? Bar
{
get { return _Bar; }
set
{
_Bar = value;
OnPropertyChanged("Bar");
}
}

public event PropertyChangedEventHandler PropertyChanged;

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

我的绑定(bind)看起来像这样:
<local:TextBoxEx MyProperty="{Binding Bar, UpdateSourceTrigger=PropertyChanged}"/>

记住:我需要一个 TwoWay 绑定(bind),所以 OneWayToSource 对我不起作用。

知道我在这里没有得到什么吗?

最佳答案

您只需将绑定(bind)设置为双向即可。但这应该是默认设置,您可以使用以下元数据相应地注册属性:

... new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
PropertyChangedCallback)

获取 TextChanged 中的表达式处理程序和手动更新源不是必需的,所以我会删除该代码。

如果你没有在绑定(bind)上显式设置模式,将使用默认模式,来自 the documentation :

Default: Uses the default Mode value of the binding target. The default value varies for each dependency property. In general, user-editable control properties, such as those of text boxes and check boxes, default to two-way bindings, whereas most other properties default to one-way bindings. A programmatic way to determine whether a dependency property binds one-way or two-way by default is to get the property metadata of the property using GetMetadata and then check the Boolean value of the BindsTwoWayByDefault property.

关于wpf - 依赖属性 - 更新源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7267840/

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