带有项源选项的组合框动态数据显示.如何选择特定项目

本文关键字:何选择 选择 项目 显示 数据 选项 动态 组合 | 更新日期: 2023-09-27 18:31:27

我有一个组合框,数据动态分配如下

<combobox 
    name="clientbox"
    itemsource={Binding}, 
    displaymemberpath="ClientName" 
    selectedvaluepath="clientid" />

我正在从数据库加载客户端详细信息并将其设置为列表框并分配给组合框,如下所示。

clientbox.DataContext = <list>

运行后,我能够在组合框中看到数据。这将选择第 0 项,但我想默认选择其他项。怎么做?

带有项源选项的组合框动态数据显示.如何选择特定项目

  clientbox.SelectedItem =  ((ComboBoxItem)clientbox.Items[1]);
  clientbox.Text = ((ComboBoxItem)clientbox.Items[1]).Content.ToString();

有几种可能性:

代码隐藏:

// Setting the 0-based index
clientBox.SelectedIndex = 1;
// Setting the item
clientBox.SelectedItem = activeClient;
// Setting the value (explanation follows..)
clientBox.SelectedValue = activeClientValue

使用 SelectedValue 属性,您可以定义用于填充ComboBox的项的属性。例如:用具有属性IdName等属性的类Client的项目填充ComboBox。如果选择一个项,则 SelectedItem 属性将是类Client的实例。通过将ComboBoxSelectedValuePath 属性设置为IdSelectedValue将始终只包含所选客户端的 id。

捆绑:

当然,您始终可以使用绑定。

<ComboBox x:Name="clientBox"
    ItemsSource={Binding ClientList}, DisplayMemberPath = "Name" 
    SelectedValuePath="Id"
    SelectedValue={Binding ActiveClient} />