1

我不知道我在这里做错了什么。我有一个ListBoxwhoDataContextItemsSource设置,但是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. 我想要的只是显示模板名称列表。用户不会更改 aTemplate中的任何数据,ListBox只需要只读即可。

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

4

2 回答 2

7

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

最好将列表设置为 DataContext,或者创建一个包含列表的 ViewModel。这样一来,您将对 Listbox 将绑定到的实例有更多的控制权。

希望这可以帮助!

于 2010-08-17T14:22:26.383 回答
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();
}

xml:

<ListBox ItemsSource="{Binding Path=MyTemplates}" Grid.Row="1" Grid.Column="1"
   Width="400" Height="300" DisplayMemberPath="Name"
   SelectedValuePath="Name"/>
于 2010-08-17T14:22:50.103 回答