更改项目源时,可编辑组合框丢失选定的值

时间:2014-11-11 13:30:07

标签: c# wpf combobox

我有一个可编辑的组合框,如果更改了项目源,则会丢失值,以便从项目源中删除当前所选项目。

代码如下:

<ComboBox x:Name="TableNameCombo"
          MinWidth="100"
          IsEditable="True"
          ItemsSource="{Binding TableNames}"
          SelectionChanged="TableNameCombo_SelectionChanged"
          Text="{Binding TableName,
                 ValidatesOnDataErrors=True,
                 UpdateSourceTrigger=PropertyChanged}" />

如果在更改项目源时我处于不同的视图中,则保留该值。 仅当使用组合框的视图处于活动状态时更改itemsource时,该值才会丢失。

请告诉我如何保留组合框值,即使它在itemsource中不存在,并且当视图包含组合框处于活动状态时项目源会发生变化

注意:

1.我认为我的意思是我有一个标签式面板,并且总体上有不同的观点     标签。

2.我不是在谈论任何后备价值。我只想     保留所选择的值,即使它不存在     组合框项目来源。

让我将问题清理为非常简单的要求, 这是我从示例应用程序中截取的屏幕截图,

enter image description here

当用户在文本框中输入项目并单击“删除项目”按钮时,该项目将从作为Combobox的itemSource的集合中删除。但是,当我这样做时,该项目不会显示在组合框中。 enter image description here

我的要求是仍然将项目保留在组合框中,即使它不在集合中。

1 个答案:

答案 0 :(得分:0)

您可以添加以下代码:

using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

public static class ComboBoxItemsSourceDecorator
{
    public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.RegisterAttached(
        "ItemsSource",
        typeof(IEnumerable),
        typeof(ComboBoxItemsSourceDecorator),
        new PropertyMetadata(null, ItemsSourcePropertyChanged));

    public static void SetItemsSource(UIElement element, bool value)
    {
        element.SetValue(ItemsSourceProperty, value);
    }

    public static IEnumerable GetItemsSource(UIElement element)
    {
        return (IEnumerable)element.GetValue(ItemsSourceProperty);
    }

    private static void ItemsSourcePropertyChanged(DependencyObject element, DependencyPropertyChangedEventArgs e)
    {
        var target = element as ComboBox;
        if (element == null)
        {
            return;
        }

        // Save original binding 
        var originalBinding = BindingOperations.GetBinding(target, ComboBox.TextProperty);

        BindingOperations.ClearBinding(target, ComboBox.TextProperty);
        try
        {
            target.ItemsSource = e.NewValue as IEnumerable;
        }
        finally
        {
            if (originalBinding != null)
            {
                BindingOperations.SetBinding(target, ComboBox.TextProperty, originalBinding);
            }
        }
    }
}

并像这样使用:

<ComboBox IsTextSearchEnabled="true" 
    IsTextSearchCaseSensitive="false"
    options:ComboBoxItemsSourceDecorator.ItemsSource="{Binding Path=Values, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"                      
    Text="{Binding Path = Value}"
    IsEditable ="True">

当ItemsSouce改变时,它只是基本保留对相同文本的绑定。

注意:使用装饰器ItemsSource,而不是buildin。