简体   繁体   English

如何将组合框绑定到 wpf 中的组合框

[英]How to binding combobox to combobox in wpf

I have two Combobox我有两个组合框

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

and

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

When I select sourceNumber = 3 (1,2,3) will be added to destinationNumber当我选择sourceNumber = 3 (1,2,3) 将被添加到destinationNumber
When I select sourceNumber = 5 (1,2,3,4,5) will be added to destinationNumber当我选择sourceNumber = 5 (1,2,3,4,5) 将被添加到destinationNumber

How can I do it ?我该怎么做 ? Thanks for helps .感谢您的帮助。

You can use converter to solve this problem.您可以使用转换器来解决此问题。

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();
        }
    }

And you must slightly change your XAML code:您必须稍微更改 XAML 代码:

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

Where myConverter is: myConverter在哪里:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM