给出以下视图模型示例
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
集合,而Template列中的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>
我想将我的集合类型(Id
)的另一个属性myobjType
传递给验证规则,如何从规则中访问该属性。我知道关于freezable以及获取视图模型的上下文的信息,但是我需要绑定到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; }
}