gpt4 book ai didi

c# - 对多个 WPF 控件应用类似的绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 16:05:51 26 4
gpt4 key购买 nike

如果已经有人问过,请提前致歉;我花了一段时间谷歌搜索和搜索堆栈溢出 - 但找不到类似的问题。

我有一个 WPF 窗口,其中有很多很多数据输入控件。所有控件都有两种方式绑定(bind)到 View 模型,并使用 IDataErrorInfo 进行验证。

这里给出了一个绑定(bind)的例子:

<TextBox >
<TextBox.Text>
<Binding Path="Street" Mode="TwoWay" NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True">
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>

此绑定(bind)与所有其他绑定(bind)之间的唯一区别是路径。

我的所有绑定(bind)都需要验证规则,以及关于何时更新的说明,因为正在进行大量跨字段验证。

我的问题是 - 我是否可以将相同的绑定(bind)应用到文本框,而无需为上述示例执行当前必须执行的所有复制/粘贴操作?

我在想也许我应该推出自己的绑定(bind)子类来处理它 - 但我不知道这是否是好的做法?

更新:我刚刚像这样尝试了绑定(bind)的子类:

 public class ExceptionValidationBinding : Binding
{
public ExceptionValidationBinding()
{
Mode = BindingMode.TwoWay;
NotifyOnValidationError = true;
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
ValidatesOnDataErrors = true;
ValidationRules.Add(new ExceptionValidationRule());
}
}

这让我的 xaml 看起来像这样:

<TextBox Text="{bindings:ExceptionValidationBinding Path=PostCode}" />

而且它似乎有效......就像我说的 - 虽然不知道这种方法是否有任何问题。

最佳答案

如果您不希望 View 的代码隐藏中有任何代码,您可以创建一个 MarkupExtension 并在您的 XAML 中使用它。下面是 MarkupExtension 的示例:

public class MyBinding : MarkupExtension
{
public string ThePath { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider)
{
Binding binding = new Binding(ThePath) {
Mode = BindingMode.TwoWay,
NotifyOnValidationError = true,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
ValidatesOnDataErrors = true
};
binding.ValidationRules.Add(new ExceptionValidationRule());
return binding;
}
}

然后您可以在 XAML 中执行此操作:

<TextBox Text="{local:MyBinding ThePath=Street}">

编辑:看起来这给出了一个运行时错误。将行 return binding; 更改为 return binding.ProvideValue(serviceProvider);。我想从 Binding 派生一个类实际上更好,但我还是会把它留在这里 :)

关于c# - 对多个 WPF 控件应用类似的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33034104/

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