【问题标题】:How to binding combobox to combobox in wpf如何在wpf中将组合框绑定到组合框
【发布时间】:2012-11-12 18:23:21
【问题描述】:

我有两个组合框

<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

我该怎么做?感谢您的帮助。

【问题讨论】:

标签: c# wpf binding .net-4.0 combobox


【解决方案1】:

你可以使用转换器来解决这个问题。

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" />

【讨论】:

  • 非常感谢您的解决方案。它工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-19
相关资源
最近更新 更多