Свойство Combobox "SelectedItem" - PullRequest
       41

Свойство Combobox "SelectedItem"

0 голосов
/ 29 апреля 2020

Я работаю над приложением и столкнулся с проблемой. У меня есть следующий Combobox (.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» - это ObservableCollection «Ingredient» (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;
    }

Список ComboBox представляет собой список объектов (ингредиентов), а не список строк. Вот почему, когда я выбираю объект, свойство " SelectedItem " не отображает выбранную строку.

Я искал в Google, я прочитал, что его (возможно) нужно использовать переопределение свойства ToString (), но я не понимаю, как это сделать.

Не могли бы вы помочь мне найти лучший способ исправить мою проблему?

PS: При необходимости, класс «ИнгредиентПровидер»

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;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...