There is a form with 3 textbox and a button. How to do in xaml, so that until all 3 fields are filled, the button will be inactive. For one field, the binding is clear, but how to do it for all three fields?

 IsEnabled="{Binding ElementName=searchString, Path=Text.Length} 
  • five
    Do not try to transfer the logic to the presentation. Add a property to the model that will return the desired result of the checks. - Alex Krass
  • 3
    standard paths: 1) property in the view model 2) multi-binding / binding + converter 3) This is a button, which means the team has CanExecute, which will disassemble the button until the condition is met. - vitidev

2 answers 2

An example of the implementation of "multibinding + converter" is one of the options specified by @vitidev.

 <!-- Где-нибудь в ресурсах --> <local:IntToBoolMultiConverter x:Key="IntToBoolMultiConverter"/> ... <Button Content="Test" Width="100"> <Button.IsEnabled> <MultiBinding Converter="{StaticResource IntToBoolMultiConverter}"> <Binding ElementName="SearchString1" Path="Text.Length"/> <Binding ElementName="SearchString2" Path="Text.Length"/> <Binding ElementName="SearchString3" Path="Text.Length"/> </MultiBinding> </Button.IsEnabled> </Button> 

And the converter itself:

 [ValueConversion(typeof(int[]), typeof(bool))] public class IntToBoolMultiConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var result = values != null && values.All(x => x is int && (int)x != 0); return result; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } 

Although, the task of the converter (true if there are no zeros) is not quite obvious by this name and it is better to give it a more specific name.

But in general, I agree with @AlexKrass - here all the same, not some kind of margin or color change, but the inclusion / disabling of the functionality, and it is better to do this through the view model.

    I can offer an option without using a converter, but with triggers.

     <StackPanel> <TextBox Name="textBox1" /> <TextBox Name="textBox2" /> <Button Name="button" Content="button"> <Button.Style> <Style TargetType="Button"> <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding ElementName=textBox1, Path=Text.Length}" Value="0" /> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="False" /> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding ElementName=textBox2, Path=Text.Length}" Value="0" /> </MultiDataTrigger.Conditions> <Setter Property="IsEnabled" Value="False" /> </MultiDataTrigger> </Style.Triggers> </Style> </Button.Style> </Button> </StackPanel>