首页 文章

以编程方式使用SelectedValue WPF选择组合框项目

提问于
浏览
0

我有一个组合框,通过Datasource(Datatable)加载 . 在一个场景中,我希望组合框加载所需的值,我将传递给combobox1.SelectedValue = custId(说它是客户详细信息) . custID在XAML中设置为SelectedValuePath . 当我设置它时,我得到一个null异常 . 我错过了什么?

我的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" />

UPDATE:

C#代码:

public customer(int custid)
{
   InitializeComponent();
   cmbcustomer.SelectedValue= custid.ToString();
}

private void cmbCustomerName_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      cmbcustid.SelectedValue= cmbcustomer.SelectedValue;
    }

4 回答

  • 0

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

    combobox1.SelectedItem =“custId”;

    要么

    combobox1.Text =“custId”;

    要么

    combobox1.SelectedIndex = combobox1.Items.IndexOf(“custId”);

    要么

    combobox1.SelectedIndex = combobox1.FindStringExact(“custId”)

  • 0

    我会建议你一个方法

    这是hackish . 这是糟糕的编码格式 .

    // 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;
    

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

  • 0

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

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

    我通过在combox_loaded事件中分配值来解决问题,因为组合框刚刚在构造函数中初始化,但它没有从数据源加载 .

相关问题