[英]WPF DataGrid - How do I use cell and row validation with DataGridTemplateColumn
How do I use cell and row validation with DataGridTemplateColumn? 如何在DataGridTemplateColumn中使用单元格和行验证?
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataType}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox SelectedItem="{Binding DataType}" ItemsSource="{Binding Source={x:Static app:ApplicationConfiguration.DataTypes}, ValidatesOnDataErrors=True}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
It's a bit of a guess, but it looks like you want to prevent certain items from being selected. 有点猜测,但是您似乎想防止选择某些项目。 The easiest way would be to remove them from the list, but you could do it using validation as follows. 最简单的方法是将它们从列表中删除,但是您可以使用验证来进行以下操作。
If the selected item is invalid, throw an exception in the Setter in the ViewModel: 如果所选项目无效,则在ViewModel的Setter中引发异常:
public object DataType
{
get { return dataType; }
set
{
if(valueNotAllowed(value))
throw new Exception(string.Format("{0} is not a valid selection", value.ToString());
dataType = value;
}
}
Then set the binding for SelectedItem to ValidateOnExceptions (note that in your question, you specified ValidatesOnErrors for the ItemsSource binding - wrong property on the wrong binding): 然后将SelectedItem的绑定设置为ValidateOnExceptions(请注意,在您的问题中,您为ItemsSource绑定指定了ValidatesOnErrors-错误的绑定上的错误属性):
<ComboBox SelectedItem="{Binding Path=DataType, ValidatesOnExceptions=True}"
ItemsSource="{Binding Source={x:Static app:ApplicationConfiguration.DataTypes}}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.