2010-08-17 47 views
1

我不知道我在做什么错在这里。我有一个ListBoxDataContextItemsSource设置,但是当我运行我的应用程序时ListBox没有任何内容。在调试时,我的获取ListBox物品的方法的第一行永远不会被击中。下面是我有:WPF,什么也没有显示在列表框中

// 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回报只是一个字符串列表 - 它需要返回Template对象的一些集合。

回答

6

您无法绑定到方法。使它成为一个财产,它应该工作。

尽管将List设置为DataContext,或者创建了一个包含列表的ViewModel,但它更好。 Thay的方式,你将更好地控制你的Listbox绑定到的实例。

希望这会有所帮助!

+1

这是干净多了!我将我的'GetTemplates'方法设置为private,并在构造函数中设置'DataContext = GetTemplates()'。然后,我只是将我的XAML中的ItemsSource设置为我的'Templates'类已有的'List'属性 - 谢谢! – 2010-08-17 14:31:48

+1

很高兴我可以帮忙;) – Arcturus 2010-08-17 14:41:46

+1

顺便说一句,如果你真的想从Xaml调用一个方法,看看ObjectDataProvider。 Bea Stollnitz有一个不错的博客: http://bea.stollnitz.com/blog/?p=22 – Arcturus 2010-08-17 14:43:20

1

当您应该使用属性时,您正尝试在绑定中调用方法。将它改为一个属性,你应该很好去。

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