带有空项的组合框?

41
假设我们有一个绑定到数据库集合的数据源。当然没有空项。如何向ComboBox中添加一个void项,以便在首次加载时用户将看到一个空字符串。我不想向集合中添加虚拟/void对象。最好在XAML中实现。有什么建议吗?

3
请注意,所提供的解决方案在绑定时无法使用。 - Cartesius00
2
我找到了解决绑定问题的方法,请参考这篇帖子:https://dev59.com/--o6XIcBkEYKwwoYSClJ - Frinavale
4个回答

46
<ComboBox Name="myComboBox" Width="200" Background="White">    
    <ComboBox.ItemsSource>    
        <CompositeCollection>
           <ComboBoxItem IsEnabled="False" Foreground="Black">Select Item</ComboBoxItem>
           <CollectionContainer Collection="{Binding Source={StaticResource DataKey}}" />    
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

编辑

正如@surfen在评论中提到的那样,使用BindingProxy是解决绑定问题的一种方法。


2
我似乎无法在ViewModel绑定场景中使其工作...有什么想法吗? - Anderson Imes
14
啊...我明白了。CompositeCollection不是可冻结的,因此无法与绑定一起使用。很不幸。 - Anderson Imes
4
我找到了解决CompositeCollection问题的方法:https://dev59.com/--o6XIcBkEYKwwoYSClJ - Frinavale
2
是的,它可以工作!我使用BindingProxy来解决绑定问题:http://tomlev2.wordpress.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/ - surfen
3
@surfen,自从你的博客搬家了,这是新的网址:http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/。 - Xuntar
显示剩余5条评论

3
<UserControl.Resources>
    <CollectionViewSource x:Key="Modules" Source="{Binding Path=Modules}" />
</UserControl.Resources>

<abv:ComboBox SelectedIndex="0" IsNullable="True"
    SelectedItem="{Binding Path=SelectedModule, Mode=TwoWay}">
    <abv:ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem Content="{DynamicResource EmptyModuleComboBox}"/>
            <CollectionContainer Collection="{Binding Source={StaticResource Modules}}" />
        </CompositeCollection>
    </abv:ComboBox.ItemsSource>
</abv:ComboBox>

public class ComboBox : System.Windows.Controls.ComboBox
{
    public static readonly DependencyProperty IsNullableProperty =
        DependencyProperty.Register("IsNullable", typeof(bool), typeof(ComboBox));

    public bool IsNullable
    {
        get { return (bool)GetValue(IsNullableProperty); }
        set { SetValue(IsNullableProperty, value); }
    }

    public ComboBox()
    {
        Loaded += ComboBox_Loaded;
    }

    void ComboBox_Loaded(object sender, RoutedEventArgs e)
    {

        if (IsNullable)
        {
            this.ItemContainerStyle = new Style();

            this.ItemContainerStyle.Setters.Add(new EventSetter()
            {
                Event = ComboBoxItem.PreviewMouseUpEvent,
                Handler = new MouseButtonEventHandler(cmbItem_PreviewMouseUp)
            });
        }
    }

    public void cmbItem_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    {
        if (Items.IndexOf(sender as ComboBoxItem) == 0)
        {
            SelectedItem = null;
        }
    }
}

什么是EmptyModuleComboBox? - Toddams

2

绑定到MVVM对象:

                        <ComboBox Name="cbbFiltres" SelectedItem="{Binding ElmtInfo, Mode=TwoWay}" Height="26" MinWidth="90" SelectedIndex="0" SelectedValuePath="Id">
                        <ComboBox.Resources>
                            <CollectionViewSource x:Key="cvsFiltres" Source="{Binding Elmts.items}"/>
                        </ComboBox.Resources>
                        <ComboBox.ItemsSource>
                            <CompositeCollection>
                                <model:tblFiltreChamps Desc="{x:Static resx:resMain.enumAucun}" Id="0"/>
                                <CollectionContainer Collection="{Binding Source={StaticResource cvsFiltres}}" />
                            </CompositeCollection>
                        </ComboBox.ItemsSource>
                    </ComboBox>

并且用于绑定:
<Label Visibility="{Binding Path=SelectedValue, ElementName=cbbFiltres, Converter={StaticResource NullToVisibility}}" />

还有一种通用的转换器:

    public class ConvNullToVisibility : IValueConverter {
    /// <summary>Convertisseur pour le Get.</summary>
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) return Visibility.Visible; // Pour annuler l'effet dans le designer: https://dev59.com/E5Dea4cB1Zd3GeqPdI-_
        return ((value == null) || (string.IsNullOrEmpty(value.ToString())) || (value.ToString() == "0")) ? Visibility.Collapsed : Visibility.Visible;
    }

    /// <summary>Convertisseur inverse, pour le Set (Binding).</summary>
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        if (value is Visibility) {
            return (((Visibility)value) == Visibility.Visible) ? true : false;
        } else return false;
    }
}

在组合框中声明SelectedValuePath非常重要。

:-)

-2

尝试使用Mahapps组合框。

xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"

  <ComboBox x:Name="bars"  **controls:TextBoxHelper.ClearTextButton="True"**
              DisplayMemberPath="Name" 
              Height="21" 
              SelectedItem="{Binding Bar}"/>

Combo Box View


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接