首页 > 解决方案 > 获取模型绑定列表框的 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而不是“数量描述价格”

任何帮助表示赞赏。

谢谢。

安德鲁

标签: c#wpf

解决方案


您将对象的全名作为 默认 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.SelectedItemasItemModel对象转换为 Content with 并将值设置为.ToString()

var selectedItem = itemsListBox.SelectedItem as ItemModel;
finalLabel.Content = selectedItem.ToString();

推荐阅读