【问题标题】:How to save the newly entered item into combobox itemssource?如何将新输入的项目保存到组合框项目源中?
【发布时间】:2015-08-04 14:59:36
【问题描述】:

我正在尝试将新项目添加到 Combobox 中。例如:如果 ComboBox itemssource 具有“一”、“二”和“三”。我可以通过将 IsEditable 属性设置为 true 来输入。需要保存在组合框中的新项目“四”。请分享这方面的信息。

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

&lt;ComboBox x:Name="combo" IsEditable="True" ItemsSource="{Binding ComboItems,Source={StaticResource ordercollection}}" Height="50" Width="150"/&gt;

后面的代码:

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

【问题讨论】:

  • 重启应用后是否有效?那么有新条目吗?
  • 这些组合项是在哪里定义的?
  • ViewModel 中定义的组合项
  • 我猜 orderCollection 是 XAML 中定义的 CollectionViewSource。我们能看到吗?我们可以看到 ComboItems 属性的代码吗?
  • 请找到编辑后的代码sn-p

标签: c# wpf combobox


【解决方案1】:

PreviewKeyDown

您的 ComboBox 未绑定到 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,只需绑定到属性。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 2012-10-27
    相关资源
    最近更新 更多