WPF MVVM Disable button when Datagrid has any error

Viewed 70

I research all the asked questions and answers but could not find any solutions.

I have a Datagrid that manipulate by the user and then save to the database. I have a Save button and I want it disabled if there is an error in the grid. Say when a user enters a character into the field that should have a number or null it should stay disabled.

This is my grid:

<DataGrid x:Name="dataGrid" ItemsSource="{Binding DataList}" SelectedItem="{Binding SelectedData}" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False">
     <DataGrid.Columns>
         <DataGridTemplateColumn Header="MustBeNumber">
             <DataGridTemplateColumn.CellTemplate>
                 <DataTemplate>
                     <TextBox Text="{Binding Path=NUMBER_FIELD, UpdateSourceTrigger=PropertyChanged}" >
                 </DataTemplate>
             </DataGridTemplateColumn.CellTemplate>
         </DataGridTemplateColumn>
     </DataGrid.Columns>
 </DataGrid>

My model (ViewModel has an ObservableCollection of this model):

public class Data : ObservableObject
{
    private int? _number_field;

    public int? NUMBER_FIELD { get { return _number_field; } set { _number_field = value; OnPropertyChanged("NUMBER_FIELD"); } }
}

I have tried this but no chance:

<Button Content="Save" Name="btnSave" Command="{Binding SaveCommand}">
     <Button.Style>
         <Style TargetType="Button">
             <Setter Property="IsEnabled" Value="False"/>
             <Style.Triggers>
                 <MultiDataTrigger>
                     <MultiDataTrigger.Conditions>
                         <Condition Binding="{Binding Path=(Validation.HasError), ElementName=dataGrid}" Value="False"/>
                      </MultiDataTrigger.Conditions>
                      <Setter Property="IsEnabled" Value="True"/>
                  </MultiDataTrigger>
             </Style.Triggers>
        </Style>
   </Button.Style>
</Button>

I also try the solution mentioned here. It works quite good. However, when a user deletes a row which has an error it lost track. When this happens the button stays disabled always.

Thank you for your time.

1 Answers

Since it's been four days past, and no one posted an answer for this, I think there is no direct and easy solution.

So I implement the solution here. I just put a functionality to reset the error count every time the model change.

It is a little bit sloppy but solves the issue.

Here is the code for those that wonder:

private void OnErrorEvent(object sender, RoutedEventArgs e)
{
    var validationEventArgs = e as ValidationErrorEventArgs;
    if (validationEventArgs.Action == ValidationErrorEventAction.Added)
    {
        errorCount++;
    }
    if (validationEventArgs.Action == ValidationErrorEventAction.Removed)
    {
        errorCount--;
    }
}
Related