简体   繁体   中英

WPF DataGrid - How do I use cell and row validation with DataGridTemplateColumn

How do I use cell and row validation with 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:

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):

<ComboBox SelectedItem="{Binding Path=DataType, ValidatesOnExceptions=True}" 
ItemsSource="{Binding Source={x:Static app:ApplicationConfiguration.DataTypes}}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM