I am new to WPF and I couldn't find solution on the web. My problem is that I want my button to be enabled only when four textboxes will not have validity errors. My code is:
<Button Content="Action" Click="Action_Click" >
<Button.IsEnabled>
<MultiBinding Converter="{StaticResource ValCon}">
<Binding ElementName="textBox1" />
<Binding ElementName="textBox2"/>
<Binding ElementName="textBox3"/>
<Binding ElementName="textBox4"/>
</MultiBinding>
</Button.IsEnabled>
</Button>
and my multi value converter is like:
class ValidityConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool b = true;
foreach (var x in values)
{
TextBox y = x as TextBox;
if (Validation.GetHasError(y))
{
b = false;
break;
}
}
return b;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
I have noticed that this is working only at the beginning. When user modifies one of the textboxes it doesn't. Does my value converter need to implement INotifyPropertyChange? What is the correct solution of doing something like this in WPF? Thanks for your help.
EDIT
I have already done something like this and it's working:
<Button Click="Button_Click" >
<Button.Style>
<Style TargetType="Button">
<Setter Property="IsEnabled" Value="False"/>
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox}" Value="False"/>
<Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox1}" Value="False"/>
<Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox2}" Value="False"/>
<Condition Binding="{Binding Path=(Validation.HasError), ElementName=textBox3}" Value="False"/>
</MultiDataTrigger.Conditions>
<Setter Property="IsEnabled" Value="True"/>
</MultiDataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
MultiBinding
are changing; they are always the same four text boxes. Those bindings evaluate once, so yourIMultiValueConverter
will only be evaluated once. You might consider using aBindingGroup
to pull all your validation rules into a single scope. – Ohaus