Disable DataGridCell if another cell is being used

2019-07-22 17:10发布

问题:

On a row inside of a datagrid, I'm trying to disable a cell/field if the cell next to it is being used or vice verse. In other words the user can only enter one or the other, if the user enters info into one cell the other should be disabled or readonly or something. How can I achieve this? Can I somehow create a converter? At the same time the user should be able to zero out that cell in case he didn't mean to enter info in that cell. Any advice is much appreciated.

 <DataGridTextColoumn Binding="{Binding Property1}" Header="Property1" />
 <DataGridTextColoumn Binding="{Binding Property2}" Header="Property2" />

-So if i enter info into property1 cell then i shouldn't be able to enter anything into property2 cell. If i enter something into property2 cell then I shouldn't be able to enter anything into property1 cell.

回答1:

A converter could work (as you mentioned). Something like this

<Window 
    ...
    xmlns:c="clr-namespace:*YourConverter'sNamespace*"
    ...
    />
<Window.Resources>
    <c:NotBlankConverter x:Key="NotBlankConverter"/>
</Window.Resources>
...
<DataGridTextColoumn 
    Binding="{Binding Property1}" 
    Header="Property1" 
    IsReadOnly="{Binding Property2, Converter={StaticResource NotBlankConverter}"
    />
...

Where your converter can look something like this

class NotBlankConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return string.IsNullOrEmpty(value);
    }
    ...
}

Update

It appears this actually will not work because of the way the IsReadOnly DP works for the DataGridTextColumn. To have a complete working solution, something from these questions needs to be implemented...

.Net v4 DataGridTextColumn.IsReadOnly seems to be faulty

DataGridTextColumn - How to bind IsReadonly?