【发布时间】: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