以编程方式使用选定值 WPF 选择组合框项



我有一个通过数据源(Datatable(加载的组合框。在这种情况下,我希望组合框加载所需的值,我将作为 combobox1 传递该值。SelectedValue = custId(假设它是客户详细信息(。custID 在 XAML 中设置为 SelectedValuePath。当我设置它时,我得到一个空异常。我错过了什么?

我的 XAML:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="332,42,0,0" Name="cmbCustomerName" VerticalAlignment="Top" Width="240" IsEditable="True" DisplayMemberPath="customername" SelectedValuePath="custid" ItemsPanel="{StaticResource cust}" SelectionChanged="cmbCustomerName_SelectionChanged" AllowDrop="True" FontWeight="Normal" Text="--Select a Customer Name--" IsSynchronizedWithCurrentItem="True" />

更新:

C# 代码:

public customer(int custid)
{
   InitializeComponent();
   cmbcustomer.SelectedValue= custid.ToString();
}
private void cmbCustomerName_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      cmbcustid.SelectedValue= cmbcustomer.SelectedValue;
    }

在这种情况下,selectedValue 不起作用,您应该改用 selectedItem,例如:

组合框1.SelectedItem = "custId";

组合框1.文本 = "custId";

组合框1.选定索引 = 组合框 1。Items.IndexOf("custId"(;

组合框1.选定索引 = 组合框 1。FindStringExact("custId"(

我会给你推荐一种方法

这是黑客。这是错误的编码格式。

// Remove the handler
cmbcustomer.SelectionChanged -= cmbCustomerName_SelectionChanged;
// Make a selection...
cmbcustomer.SelectedIndex = combobox1.Items.IndexOf(custid.ToString()); //<-- do not want to raise
// SelectionChanged event programmatically here
// Add the handler again.
cmbcustomer.SelectionChanged += cmbCustomerName_SelectionChanged;

作为临时解决方案,您可以尝试一下

等待访问 ComboBox es 的任何属性,直到它们被加载:

private void cmbCustomerName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if(cmbcustid != null && cmbcustid.IsLoaded && cmbcustomer != null && cmbcustomer.IsLoaded)
        cmbcustid.SelectedValue = cmbcustomer.SelectedValue;
}

我通过在 combox_loaded 事件中分配值解决了这个问题,因为组合框刚刚在构造函数中初始化,但它不是从数据源加载的。

最新更新