默认选择在wpf中不起作用

时间:2014-12-08 14:44:34

标签: c# wpf combobox

这里我使用了一个wpf ComboBox控件并使用数据源绑定它。     但我的组合框无法设置我给出的第一个索引的默认选择     在绑定的时候manualy。这里我的代码可以告诉我如何在combox框中设置默认项目。

// XAML中

<ComboBox Height="23" HorizontalAlignment="Left" Margin="142,11,0,0" Name="cmbProductType" VerticalAlignment="Top" Width="180" ItemsSource="{Binding}" />

//代码

private void Window_Loaded(object sender, RoutedEventArgs e)
    {

        ClsControl.GetProductTypeList(cmbProductType);
    }
 public static void GetProductTypeList(ComboBox ddlProductType)//Add By Sandeep On 11-03-2013
    {
        try
        {
            DataTable dtProductType = null;
            try
            {
                ClsDataLayer objDataLayer = new ClsDataLayer();
                dtProductType = objDataLayer.ExecuteDataTable("COMNODE_PROC_GetProductTypeList");
                if (dtProductType != null && dtProductType.Rows.Count > 0)
                {
                    DataRow drCardType = dtProductType.NewRow();
                    drCardType[0] = -1;
                    drCardType[1] = "< -- Select Card Type -- >";
                    ddlProductType.SelectedValue = -1;
                    dtProductType.Rows.InsertAt(drCardType, 0);
                    ddlProductType.ItemsSource = dtProductType.DefaultView;
                    ddlProductType.DisplayMemberPath = "PRODUCT_TYPE";
                    ddlProductType.SelectedValuePath = "PRODUCT_TYPE_ID";
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        catch
        {
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试将您的XAML更新为:

<ComboBox Height="23" 
          HorizontalAlignment="Left" 
          Margin="142,11,0,0" 
          Name="cmbProductType" 
          VerticalAlignment="Top" 
          Width="180" 
          ItemsSource="{Binding}" 
          IsSynchronizedWithCurrentItem="True" />

此外,当您选择项目时,请使用SelectedIndex:

            ddlProductType.SelectedIndex = 0;
            dtProductType.Rows.InsertAt(drCardType, 0);
            ddlProductType.ItemsSource = dtProductType.DefaultView;
            ddlProductType.DisplayMemberPath = "PRODUCT_TYPE";
            ddlProductType.SelectedValuePath = "PRODUCT_TYPE_ID"