c# - 如何将新输入的项目保存到组合框项目源中?

标签 c# wpf combobox

我正在尝试将新项目添加到 Combobox 中。例如:如果 ComboBox 项目源具有“一个”、“两个”和“三个”。我可以通过将 IsEditable 属性设置为 true 来键入。需要保存在组合框中的新项目“四”。请就此分享。

<Window.Resources>
    <local:OrderInfoRepositiory x:Key="ordercollection"/>
</Window.Resources>

<ComboBox x:Name="combo" IsEditable="True" ItemsSource="{Binding ComboItems,Source={StaticResource ordercollection}}" Height="50" Width="150"/>

代码隐藏:

void combo_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        var combo=(sender as ComboBox);
        (combo.DataContext as OrderInfoRepositiory).ComboItems.Add(combo.Text);
    }


private ObservableCollection<string> comboItems = new ObservableCollection<string>();
    public ObservableCollection<string> ComboItems
    {
        get { return comboItems; }
        set 
        { 
            comboItems = value;
            RaisePropertyChanged("ComboItems");
        }
    }

public OrderInfoRepositiory()
    {
        orderCollection = new ObservableCollection<OrderInfo>();
        OrderInfoCollection = GenerateOrders();
        foreach (OrderInfo o in orderCollection)
        {
            comboItems.Add(o.Country);
        }
    }

最佳答案

PreviewKeyDown

您的 ComboBox 未绑定(bind)到 EventHandler comboBox_PreviewKeyDown

您真的要使用 PreviewKeyDown 吗? 使用 PreviewKeyDown comboBox.Text 在排除您按下的键之前仍然有文本。请改用 KeyDown。

每个按键都会添加新的和旧的键入字母。 输入“Hello World”将以 H、He、Hel、Hell 等结尾。 检查 Key.Return 以在完成时添加项目或使用按钮。然后您仍然可以使用 PreviewKeyDown 事件。

void combo_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        var combo = (sender as ComboBox);
        (combo.DataContext as OrderInfoRepository).ComboItems.Add(combo.Text);
    }
}

数据上下文

您正在将 DataContext 转换为 OrderInfoRepositiory 但您的代码中没有赋值。

添加到您的 ComboBox:

DataContext="{Binding Source={StaticResource ordercollection}}"

然后你可以改变你的ItemsSource:

ItemsSource="{Binding ComboItems}"

我更喜欢在我的底层 ViewModel 中设置 OrderInfoRepositiory,这样您就不需要 StaticResource,只需绑定(bind)到该属性即可。

<ComboBox x:Name="combo" IsEditable="True" DataContext="{Binding Source={StaticResource ordercollection}}" ItemsSource="{Binding ComboItems}" Height="50" Width="150" KeyDown="combo_PreviewKeyDown"/>

关于c# - 如何将新输入的项目保存到组合框项目源中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31812739/

相关文章:

wpf - 您可以将非字符串标记值放入 xaml 声明中的组合框吗?

c# - 无法生成:Microsoft/aspnetcore的 list :2.1找不到Visual Studio 7.5.2 Mac OS X

c# - 自定义计数器文件 View 内存不足

c# - 具有同一接口(interface)的两个不同实例的 StructureMap Autowiring

c# - 添加键绑定(bind)列表

c# - 跳过导航历史记录中的 View

c# - "Is there any way to access a pixel by in an image by particular position like(x,y) in opencvforunity"

c# - 错误 : The calling thread cannot access this object because a different thread owns it

java - 在组合框中复制文本 Java

java - 如何从文本文件填充Java中的两个组合框?