代码之家  ›  专栏  ›  技术社区  ›  Sarah Vessels

WPF,列表框中没有显示任何内容

  •  1
  • Sarah Vessels  · 技术社区  · 14 年前

    我不知道我在这里做错了什么。我有一个 ListBox 谁的 DataContext ItemsSource 已设置,但 列表框 当我运行应用程序时。在调试时,我的方法的第一行用于获取 列表框 永远不会被击中。以下是我的资料:

    // 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 . 我只想显示一个模板名称列表。用户不会更改 模板 , the 列表框 只需要是只读的。

    模板还具有 Data 稍后将在此显示的属性 列表框 所以我不想 GetTemplates 只返回字符串列表——它需要返回 模板 物体。

    2 回复  |  直到 14 年前
        1
  •  7
  •   Arcturus    14 年前

    不能绑定到方法。把它变成一个财产,它应该能工作。

    但最好将列表设置为DataContext,或创建一个保存列表的ViewModel。这样,您就可以更好地控制列表框将绑定到的实例。

    希望这有帮助!

        2
  •  1
  •   Metro Smurf    14 年前

    当应该使用属性时,您正试图调用绑定中的方法。把它改成一个财产,你就可以走了。

    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"/>