【问题标题】:WPF item.Content.ToString() / ListBox CodeWPF item.Content.ToString() / 列表框代码
【发布时间】:2016-01-30 18:37:12
【问题描述】:

我是 c# 和 WPF 的新手,ListBoxItem.Content 属性有问题:

ListBoxItem itm = new ListBoxItem();
itm.Content = "klant aantalConsumpties";
listBoxOverzicht.Items.Add(itm);

我做错了什么? 这是我的代码:

foreach (var item in listBoxOverzicht.Items)
{ 
     if (item.ToString().Contains(klant))                       
     { 
          MessageBoxResult result= MessageBox.Show("Er is reeds een klant met als naam " + item.Content.ToString() + ".\n" +
           "Klik op JA als je de consumpties "+
           "wilt toevoegen aan deze klant.\n" + 
           "Klik op NEE als je het om nieuwe klant gaat.\n"+
           "Klik Annuleren om input te wijzigen.","Opdracht 2", 
            MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);

          switch (result)
          { 
               case etc....

我收到消息后无法使用item.Content.ToString()

'object'不包含'Content'的定义并且没有扩展 可以找到接受“对象”类型的第一个参数的方法(是 你缺少 using 指令或程序集引用?)

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    只需删除ContentToString()就够了:

    item.ToString()
    

    如果你只想要特定的属性,试试这个:

    MessageBox.Show((item as Model).Name.ToString());
    

    最后在你的情况下,因为你想要ListBoxItemContent 属性,你应该试试这个:

    MessageBox.Show((item as ListBoxItem).Content.ToString());
    

    【讨论】:

    • FAN-TAS-TIC。非常感谢!现在效果很好!
    【解决方案2】:

    您可以尝试使用简单的 item.ToString() 而不是假设它是一个简单的文本列表框项目。

    如果您要显示更复杂的对象,则可以强制转换为对象并显示适当的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-11
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多