2012-11-24 85 views
-1

我有兩個組合框如何綁定組合框組合框在WPF

<ComboBox x:Name="sourceNumber"> 
    <ComboBoxItem Content="1"/> 
    <ComboBoxItem Content="2"/> 
    <ComboBoxItem Content="3"/> 
    <ComboBoxItem Content="4"/> 
    <ComboBoxItem Content="5"/> 

<ComboBox x:Name=destinationNumber ItemsSource="{Binding Source={sourceNumber.SelectedIndex}"/> 

當我選擇sourceNumber = 3(1,2,3)將被添加到destinationNumber
當我選擇sourceNumber = 5(1,2,3,4,5)將被添加到destinationNumber

我該怎麼辦呢?感謝您的幫助。

+0

[?你嘗試過什麼(http://mattgemmell.com/2008/12/08/what-you-you-tried /) –

回答

0

您可以使用轉換器來解決這個問題。

public class ComboBoxItemsSourceConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      if(value != null && value is int) 
      { 
       int max = (int)value; 
       if (max == -1) return null; 
       return Enumerable.Range(1, max + 1); 
      } 
      else 
       return null; 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 
    } 

而且你必須稍微改變你的XAML代碼:

<ComboBox x:Name="destinationNumber" 
        ItemsSource="{Binding Path=SelectedIndex, ElementName=sourceNumber, Converter={StaticResource myConverter}}"/> 

其中myConverter是:

<local:ComboBoxItemsSourceConverter x:Key="myConverter" /> 
+0

非常感謝你的解決方案。它工作正常。 – truvali89