“ SelectedItem”组合框属性

时间:2020-04-29 06:43:25

标签: c# wpf mvvm combobox selecteditem

我正在开发一个应用程序,但是遇到了问题。 我有以下组合框(.xaml)

<ComboBox ItemsSource="{Binding IngredientListeSource}"                              
          SelectedItem="{Binding SelectedIngredient}"
          IsEditable="True" IsTextSearchCaseSensitive="False">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
               <TextBlock Text="{Binding Name}"/>
               <TextBlock Text=" ("/>
               <TextBlock Text="{Binding IDmesure}"/>
               <TextBlock Text=")"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>

“ IngredientListeSource”是“ Ingredient”(ObservableCollection)的ObservableCollection,我在ViewModel中填充了以下代码

private List<Ingredient> getIngredientListeSource()
    {
        List<Ingredient> itemListe = new List<Ingredient>();

        foreach (var item in IngredientProvider.selectAll())
        {
            itemListe.Add(new Ingredient 
            {
                Name = item.Name,
                IDmesure = item.IDmesure,
            });
        }

        return itemListe;
    }

组合框的列表是对象(成分)列表,而不是字符串列表。这就是为什么当我选择一个对象时,“ SelectedItem”属性不会显示所选字符串的原因。

我在google上寻找,我读到它(可能)需要使用ToString()属性的重写,但我不知道该怎么做。

您能帮我找到解决问题的最佳方法吗?

PS:如有必要,“ IngredientProvider”类

public static List<Ingredient> selectAll()
    {
        List<Ingredient> list = new List<Ingredient>();
        DBUtils dBUtils = new DBUtils();
        MySqlConnection connection = dBUtils.initialize();
        bool stateConnection = dBUtils.openConnection(connection);

        string query = "SELECT ingredient.Name AS NameIngredient, mesure.Name AS NameMesure FROM ingredient " +
                "INNER JOIN mesure ON ingredient.IDmesure = mesure.IDmesure";

        //Open connection
        if (stateConnection == true)
        {
            //Create Command
            MySqlCommand cmd = new MySqlCommand(query, connection);

            //Create a data reader and Execute the command
            MySqlDataReader dataReader = cmd.ExecuteReader();

            while (dataReader.Read())
            {
                list.Add(new Ingredient
                {
                    Name = dataReader["NameIngredient"].ToString(),
                    IDmesure = dataReader["NameMesure"].ToString(),
                });
            }
        }
        dBUtils.closeConnection(connection);
        return list;
    }

0 个答案:

没有答案
相关问题