我正在开发应用程序,但是遇到了问题。我有以下组合框(.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;
}
ComboBox的列表是一个对象(成分)列表,而不是字符串列表。这就是为什么当我选择一个对象时,“ 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;
}
绑定到集合时,如果未指定任何内容,则将ToString()
结果用于显示对象。
您可能知道,c#中的所有对象都源自类型object
。如果您看一下,ToString()
是object
类公开的公共方法之一。此外,该方法标记为virtual
。这意味着可以在派生类中重写它。
AsPas,