c# - 获取模型绑定列表框的 SelectedItem 字符串表示
问题描述
我目前正在开发 WPF 应用程序。我正在尝试获取模型绑定列表框的 SelectedItem 的字符串表示形式。
模型:
public class ItemModel
{
public string Quantity { get; set; }
public string Description { get; set; }
public string Price { get; set; }
}
当用户单击“添加按钮”时:
ItemModel item = new ItemModel
{
Quantity = qtyTextBox.Text,
Description = descriptionTextBox.Text,
Price = priceTextBox.Text
};
itemsListBox.Items.Add(item);
单击其他按钮时,我希望更新标签。这是我到目前为止的位置:
finalLabel.Content = itemsListBox.SelectedItem;
这只是打印:< Namespace >.ItemModel而不是“数量描述价格”
任何帮助表示赞赏。
谢谢。
安德鲁
解决方案
您将对象的全名作为 默认 Object.ToString() 方法
ToString 方法的默认实现返回 Object 类型的完全限定名
因此,您需要重写 Object.ToString() 方法。
对于类中的覆盖.ToString()
方法ItemModel
,您指定所需的字符串表示。
public class ItemModel
{
public string Quantity { get; set; }
public string Description { get; set; }
public string Price { get; set; }
public override string ToString()
{
return String.Format("Quantity: {0}, Description: {1}, Price: {2}", this.Quantity, this.Description, this.Price);
}
}
接下来,您将itemsListBox.SelectedItem
asItemModel
对象转换为 Content with 并将值设置为.ToString()
。
var selectedItem = itemsListBox.SelectedItem as ItemModel;
finalLabel.Content = selectedItem.ToString();
推荐阅读
- python-2.7 - 无法在 Python 中的字符串列表上运行 type(x)
- c++ - 当我输入一个非整数值时,我的二次方程代码终止,我怎样才能让它正确循环?
- python - 使用循环描述多个条件
- android - 启用谷歌应用签名后生成的 11 字符哈希码不起作用
- python - 为什么 pytorch 没有为我最小化 x*x ?
- javascript - 创建简单的计算器
- c++ - 将 extern C 关键字用于 C++ 中的特定标头是否允许从 void* 转换为 char*?
- c++ - 如何制作和使用makefile winidows Nomad open solver
- javascript - 页面加载时触发一次点击
- mongodb - Mongo DB 更新查询