gpt4 book ai didi

c# - 依赖属性绑定(bind)和更新到自定义控件——它更新,但显然不是两种方式?

转载 作者:行者123 更新时间:2023-11-30 18:40:07 24 4
gpt4 key购买 nike

View 模型:

public class MyViewModel : INotifyPropertyChanged
{
public string MyText { ... }
}

XAML:

<my:MySpecialTextBox Text="{Binding MyText}" />

自定义控件:

public class MySpecialTextBox : TextBox
{
static MySpecialTextBox()
{
TextProperty.OverrideMetadata(typeof(MySpecialTextBox),
new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = true,
DefaultValue = string.empty,
PropertyChangedCallback = OnTextPropertyChanged
});
}

private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = d as MySpecialTextBox;

if (control != null)
{
control.Text = SomeAdjustedValue((string)e.NewValue);
}
}
}

问题在于,虽然自定义控件中的 DependencyProperty 确实进行了适当调整,但它并未更新 ViewModel。我意识到,由于 SomeAdjustedValue 的命名,这似乎应该是 CoerceValueCallback,但 Coercion 也不会更改 ViewModel 值。如果它是 OnTextPropertyChanged 回调的触发器,我似乎无法更新我的 ViewModel 中的值......我做了一个调试跟踪,它没有第二次使用新值通过 ViewModel。不确定在这里做什么来解决这个问题。

最佳答案

在 FrameworkPropertyMetadata 中,您可以使用不同的构造函数。将其中一个与 FrameworkPropertyMetadataOptions 参数一起使用。 FrameworkPropertyMetadataOptions.BindsTwoWayByDefault 选项将默认打开双向绑定(bind),否则它只是一种方式。

编辑:所以你做到了,我应该在生病时停止尝试回答问题。

关于c# - 依赖属性绑定(bind)和更新到自定义控件——它更新,但显然不是两种方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8745483/

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