Monday, 6 April 2009


I wanted to control the IsEnabled property of a Button based on the properties of two other controls.
Specifically I wanted to only enable the LogIn button if both the Site combobox and UserName textbox had a value available.

I created a MultiBinding for the Button like this:
   <MultiBinding Converter="{StaticResource loginConverter}">
      <Binding ElementName="xSite" Path="SelectedIndex"/>
      <Binding ElementName="xUsername" Path="Text"/>

And a IMultiValueConverter like this:
public class LoginConverter : IMultiValueConverter
   public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
      // SelectedIndex of the ComboBox
      int selectedIndex = (int)values[0];
      // Length of Text in TextBox
      int selectedLength = ((string)values[1]).Length;
      // Only enable Button if both Combo and TextBox have data
      if (selectedIndex == -1 || selectedLength==0)
         return false;
         return true;
   public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
      throw new NotImplementedException();

The array of object[] values are presented in the same order as the Bindings within the MultiBinding.

Finally here is an example of using MultiBinding with StringFormat.

No comments: