wpf - 无法共享 ValidationRules 时在 DataTemplates 中重复使用的绑定(bind)实例

标签 wpf data-binding datatemplate validationrules

我正在寻找解决方案和/或为什么在 DataTemplate 中共享 Binding 实例的合理性。这最终归结为这样一个事实,即在 DataTemplate 中,似乎没有办法为每个生成的控件强制在 DependencyProperty 上创建一个新的绑定(bind)实例。在所有情况下,这可能是一个公平且良好的假设,除非有 ValidationRules 表示该控件实例的特定内容。

详细说明(我可以提供代码,但我认为没有必要),我使用 IsEnabled 上的 DependencyPropertyDescriptor 来更新属于 TextBox.Text 绑定(bind)、DatePicker.Text 绑定(bind)或 ComboBox.SelectedValue 绑定(bind)的一个或多个 ValidationRules等。这个想法是,当未启用控件时,验证将不同或不受欢迎。

因此,ValidationRule 的 IsEnabled 状态特定于单个控件,并且因为 ValidationRule 集合是 Binding 的一部分并且正在共享 Binding 实例 - 每个最终共享该绑定(bind)的控件都将更新/覆盖之前的 IsEnabled 值由先前生成的控件的 IsEnabled 值应用。

IsEnabled 只是 ValidationRule(另一个自定义 IsRequired DependencyProperty)中的至少两个属性之一,它们表示应用了 Binding 的控件的状态。在 DataTemplate 之外工作时(IE:Binding 实例不共享),这非常有效,并且可以根据控件的状态忽略/更改验证逻辑。我并没有拒绝替代方案,但确实觉得这一直是(抛开这个问题)一个非常灵活和动态的选项,它允许 Binding 实例 ValidationRule 和规则的控制更改状态毫不费力地发展。这也使我能够避免其他明显但更难看的选项,例如创建多个绑定(bind),每个绑定(bind)代表 ValidationRule 的控件属性的组合之一,并在 DependencyPropertyDescriptor 触发时切换整个绑定(bind)。颤抖

任何想法都非常感谢!

最佳答案

我建议你使用x:Shared attribute在 DataTemplate 定义中。

<DataTemplate x:Key="DataTemplateKey" DataType="{x:Type YourType}" x:Shared="False">
    ...
</DataTemplate>

由于您使用它,WPF 将在每个请求上创建一个新的 DataTemplate 实例。

关于wpf - 无法共享 ValidationRules 时在 DataTemplates 中重复使用的绑定(bind)实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10325407/

相关文章:

wpf - 如何在 ContextMenu 内为 MenuItem 设置 CommandTarget?

c# - 如何绑定(bind)自定义依赖属性来控制 View 模型?

c# - 错误绑定(bind) isEnabled 到 xaml 中的按钮

c# - WPF DataGrid 绑定(bind)性能问题

c# - 在 WPF 中继承样式

wpf - 将 WPF ComboBox 绑定(bind)到 ListBox DataTemplate 中的不同 ItemsSource

c# - 我最近开始自己学习 WPF。声明 Name 与 x :Name? 时有什么区别

c# - 从显示下拉列表不是默认值的下拉列表中捕获值

wpf - ListBox TwoWay 绑定(bind)到 SelectedItem

c# - 在代码中获取 DynamicResource