【问题标题】:Binding to different property of bound object in Validation Rule在验证规则中绑定到绑定对象的不同属性
【发布时间】:2020-02-24 22:59:43
【问题描述】:

给出以下视图模型示例

public class MyViewModel
{
  public ObservableCollection<MyObjType> BoundItems { get; }
}

MyObjType

public class MyObjType
{
  public string Name { get; set; }
  public int Id { get; set; }
}

我已将验证规则添加到 DataGrid 列,其中 DataGrid 绑定到我的 ViewModel 中的 BoundItems 集合,并且模板列中的 Text 属性绑定到 Name。

<DataGrid ItemsSource="{Binding BoundItems}">
      <DataGrid.Columns>
             <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TexBox>
                          <TextBox.Text>
                            <Binding Path="Name" ValidatesOnDataErrors="True">
                              <Binding.ValidationRules>
                                <xns:MyValidationRule>
                                  <xns:MyValidationRule.SomeDependencyProp>
                                    <xns:SomeDependencyProp SubProp={Binding Id} /> <!-- Not Working -->
                                  </xns:MyValidationRule.SomeDependencyProp>
                                </xns:MyValidationRule>
                              </Binding.ValidationRules>
                            </Binding>
                          </TextBox.Text>
                        </TextBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            ...
      </DataGrid.Columns>
</DataGrid>

我想将我的集合类型 (MyObjType) 的另一个属性 Id 传递给验证规则,如何从规则中访问它。我知道可冻结并获取视图模型的上下文,但我需要绑定到 Datagrid 的集合类型的另一个属性。

ValidationRule 和 SomeDependencyProp 仿照此处的示例:https://social.technet.microsoft.com/wiki/contents/articles/31422.wpf-passing-a-data-bound-value-to-a-validation-rule.aspx

public class SomeDependencyProp : DependencyObject
{
  public static readonly SubPropProperty =
     DependencyProperty.Register("SubProp", typeof(int),
     typeof(SomeDependencyProp), new FrameworkPropertyMetadata(0));

  public int SubProp{
    get { return (int)GetValue(SubPropProperty ); }
    set { SetValue(SubPropProperty, value); }
  }
}

public class MyValidationRule: System.Windows.Controls.ValidationRule
{
  public override ValidationResult Validate(object value, CultureInfo cultureInfo) 
  {
    ...
  }

  public SomeDependencyProp SomeDependencyProp { get; set; }
}

【问题讨论】:

  • 你能告诉我们MyValidationRule.SomeDependencyProp的定义吗?请编辑您的问题并将该代码添加为文本。
  • @EdPlunkett 添加了验证规则

标签: c# wpf xaml data-binding


【解决方案1】:

这种情况的解决方案是使用 BindingProxy。

【讨论】:

  • 效果很好。我已经有一个 BindingProxy,我想我只是把它放在了错误的控件上(我把它放在了 DataGrid 上)。谢谢,这很好用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多