Afaq
Afaq

Reputation: 1155

Binding multiple elements to a single Control

I have two textbox. Textbox A and Textbox B.

I want to bind these two text boxes to a single command button Button C.

That is if text of any the two text box is changed by the user then only the command button should get active.

Its really easy to achieve the above from Code Behind file but I was wondering that is it possible to bind a single control Button C to two elements Textbox A and Textbox B and achieve the needed through XAML.

Thanks and Regards.

Upvotes: 0

Views: 969

Answers (3)

Alberto
Alberto

Reputation: 15941

If you want to enable the button if any of the two textboxes has text, you can use a MultiDataTrigger:

<TextBox x:Name="TextBoxA" />
<TextBox x:Name="TextBoxB" />

<Button x:Name="ButtonC">
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding Text, ElementName=TextBoxA}" Value=""/>
                        <Condition Binding="{Binding Text, ElementName=TextBoxB}" Value=""/>
                    </MultiDataTrigger.Conditions>
                    <Setter Property="IsEnabled" Value="False" />
                </MultiDataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

Upvotes: 5

Jimmy
Jimmy

Reputation: 3264

bind IsEnabled of button to a boolean property

code is not compiled or tested.

public bool IsButtonEnabled
{       
  get
  {
    return !String.IsNullorEmpty(String1) && !String.IsNullorEmpty(String2);
  }

}

Make sure propertychanged for IsButtonEnabled is fired when the strings are changed

  public string String1
  {
      //get should be here
      set
     {
       _string1 = value;
       OnPropertyChanged("IsButtonEnabled");
       OnPropertyChanged("String1");
      }
  }

Upvotes: 0

Spook Kruger
Spook Kruger

Reputation: 367

My Suggestion is as follows:

Have TextBoxA bind to Field1 and TextBoxB bind to Field2 and bind the Command of ButtonC to a relay command. Ensure that you implement the CanExecuteMethod Articles here: MSDN Article on RelayEvents and here: Implementation of RelayCommand

In the canExecute method have an implementation that looks something like this:

public bool CanExecuteButtonC(object a)
{
   If (!string.IsNullOrEmpty(Field1) && !string.IsNullorEmpty(Field2))
    return true;

   return false;
}

if the canExecute method returns false, the button will automatically be disabled, and if returns true it will be activated.

Upvotes: 0

Related Questions