Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind silverlight combobox to the result of another combobox

I want to do something like this:

<combobox x:Name="cboCustomers" ItemsSource="{Binding Path=Data.Customers}"/>
<combobox x:Name="cboInvoices"ItemsSource="{cboCustomers.SelectedItem.Invoices}"/>

Anyone know of a way to do something like this in Silverlight 3? I am sure there is some information about it out there, but I am having bad luck with Google in forming the question.

like image 204
JasonRShaver Avatar asked Dec 02 '25 19:12

JasonRShaver


1 Answers

You need to specify ElementName on the second binding:

<combobox x:Name="cboCustomers" ItemsSource="{Binding Data.Customers}"/>
<combobox x:Name="cboInvoices"ItemsSource="{Binding SelectedItem.Invoices, ElementName=cboCustomers}"/>

If you also want the second combobox to be disabled until something has been selected in the first combobox you can bind the IsEnabled property of the second combobox to the SelectedItem property of the first combobox through a converter.

Add this class to your project:

public class NullToBooleanConverter : IValueConverter {

  public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) {
    if (targetType == typeof(Boolean))
      return value != null;
    throw new NotSupportedException("Value converter can only convert to Boolean type.");
  }

  public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) {
    throw new NotSupportedException("Value converter cannot convert back.");
  }

}

Add an instance of this class to the resource dictionary of your user control (local is the namespace tag for the namespace of the converter):

<UserControl.Resources>
  <local:NullToBooleanConverter x:Key="NullToBooleanConverter"/>
</UserControl.Resources>

Then you can add this to the second combobox:

IsEnabled="{Binding SelectedItem, ElementName=cboCustomers, Converter={StaticResource NullToBooleanConverter}}"
like image 150
Martin Liversage Avatar answered Dec 04 '25 22:12

Martin Liversage