【问题标题】:WPF, nothing shows up in ListBoxWPF,列表框中没有显示任何内容
【发布时间】:2010-08-17 14:18:43
【问题描述】:

我不知道我在这里做错了什么。我有一个ListBox,其DataContextItemsSource 已设置,但是当我运行我的应用程序时ListBox 中没有任何内容。调试时,我为ListBox 获取项目的方法的第一行永远不会被命中。这是我所拥有的:

// Constructor in UserControl
public TemplateList()
{
    _templates = new Templates();
    InitializeComponent();
    DataContext = this;
}

// ItemsSource of ListBox
public List<Template> GetTemplates()
{
    if (!tryReadTemplatesIfNecessary(ref _templates))
    {
        return new List<Template>
            {
                // Template with Name property set:
                new Template("No saved templates", null)
            };
    }
    return _templates.ToList();
}

这是我的 XAML:

<ListBox ItemsSource="{Binding Path=GetTemplates}" Grid.Row="1" Grid.Column="1"
         Width="400" Height="300" DisplayMemberPath="Name"
         SelectedValuePath="Name"/>

Template 类的实例上,有一个Name 属性,它只是一个string。我想要的只是显示模板名称列表。用户不会更改Template 中的任何数据,ListBox 只需要只读即可。

模板还有一个Data 属性,稍后我将在这个ListBox 中显示它,所以我不想让GetTemplates 只返回一个字符串列表——它需要返回一些@ 集合987654336@ 个对象。

【问题讨论】:

    标签: c# wpf xaml listbox itemssource


    【解决方案1】:

    您不能绑定到方法。让它成为一个属性,它应该可以工作。

    最好将 List 设置为 DataContext,或者创建一个包含该列表的 ViewModel。这样一来,您将可以更好地控制您的 Listbox 将绑定到的实例。

    希望这会有所帮助!

    【讨论】:

    • 这样干净多了!我将GetTemplates 方法设为私有,并在构造函数中设置DataContext = GetTemplates()。然后我在我的 XAML 中将 ItemsSource 设置为我的 Templates 类已经拥有的 List 属性——谢谢!
    • 顺便说一句,如果您真的希望从 Xaml 调用方法,请查看 ObjectDataProvider。 Bea Stollnitz 有一个不错的博客:bea.stollnitz.com/blog/?p=22
    【解决方案2】:

    当您应该使用属性时,您正试图调用绑定中的方法。将其更改为属性,您应该一切顺利。

    public List<Template> MyTemplates {get; private set;}
    
    public TemplateList()
    {
        InitializeComponent();
        SetTemplates();
        DataContext = this;
    }
    
    // ItemsSource of ListBox
    public void SetTemplates()
    {
        // do stuff to set up the MyTemplates proeprty
        MyTemplates = something.ToList();
    }
    

    Xaml:

    <ListBox ItemsSource="{Binding Path=MyTemplates}" Grid.Row="1" Grid.Column="1"
       Width="400" Height="300" DisplayMemberPath="Name"
       SelectedValuePath="Name"/>
    

    【讨论】:

      猜你喜欢
      • 2016-04-01
      • 2014-09-29
      • 2020-03-24
      • 2014-07-21
      • 2016-02-19
      • 2020-06-16
      • 2021-02-05
      • 2018-10-10
      • 1970-01-01
      相关资源
      最近更新 更多