Reputation: 349
I have some (>20) controls in a window, each is bound to a property of a ViewModel.
The ViewModel implements IDataErrorInfo
, in order to do some validations, and it works well.
Now I add a button something like "Commit" to the window. I want to disable the button if any control has validation error.
Although I can use DataTrigger
to do the trick like this:
<Button Content="Commit">
<Button.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=control1, Path=(Validation.HasError)}" Value="True">
<Setter Property="Button.IsEnabled" Value="False" />
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=control2, Path=(Validation.HasError)}" Value="True">
<Setter Property="Button.IsEnabled" Value="False" />
</DataTrigger>
<!-- DataTriggers for control3, 4, 5... -->
</Style.Triggers>
</Style>
</Button.Style>
</Button>
That'll be a long XAML code because I have 20+ controls in this window, so I wonder is there a better solution?
Upvotes: 1
Views: 800
Reputation: 1439
Maybe you should create a command in ViewModel. Something like this:
class ViewModel
{
public ICommand CommitCommand{ get; private set; }
public ViewModel()
{
CommitCommand = new RelayCommand(Commit, CanCommit);
}
private void Commit(object parameter)
{
// button click handler
}
private bool CanCommit(object parameter)
{
// check: view model has errors
}
}
Implement ICommand interface you can get here: Wpf Tutorial
Xaml code:
<Button Command={Binding CommitCommand}/>
Upvotes: 3