【问题标题】:C# WPF DataTemplate bindingC# WPF 数据模板绑定
【发布时间】:2012-01-22 05:36:19
【问题描述】:

我将MyListBox 绑定到 MyObject 实例列表。 MyObject 包含一个名为 TextField 的字符串字段。我想将 listBox 中的每个项目绑定到MyObject.TextField。我的代码如下,但它不起作用。

<ListBox Name="MyListBox">
    <ListBox.ItemTemplate>
            <DataTemplate>                
                    <TextBlock Text="{Binding Path=TextField}"></TextBlock>
            </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这样做的正确方法是什么?

已解决:我的对象类的 TextField 不是属性

【问题讨论】:

  • 要么发布正确的答案并接受它,要么删除问题。

标签: c# wpf binding datatemplate


【解决方案1】:

确保设置 ListBox 的ItemsSource:

<ListBox Name="MyListBox" ItemsSource="{Binding theList}">
    <ListBox.ItemTemplate>
            <DataTemplate>                
                    <TextBlock Text="{Binding TextField}" />
            </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

【讨论】:

  • 这样它甚至不绑定到列表。
  • @HelloWorld Window/UserControl 的 DataContext 是否设置正确?
  • 我不太明白你的意思
  • @HelloWorld 对象的 DataContext 告诉它在哪里寻找绑定。您必须在 Window 或 UserControl 上设置它,否则所有绑定都会失败。
  • 你能告诉我一个如何为Window设置DataContext的例子吗?
【解决方案2】:

编辑:我在 VS 2010 中尝试了解决方案...这里是代码

首先创建自己的类,例如人员类

class Person
{

    public Person(String name)
    {
        this.name = name;
    }

    String name;
    public String Name
    {
        get { return name; }
        set { name = value; }
    }
}

然后你像这样在 xaml 中创建列表框

<ListBox Height="222" HorizontalAlignment="Left" Margin="105,28,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=Name}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

xaml 中的注释 Path=Name 是您要在列表框中显示的属性

在代码隐藏文件中,输入以下代码

        List<Person> persons = new List<Person>();
        persons.Add(new Person("person 1"));
        persons.Add(new Person("person 2"));

【讨论】:

  • 在initializecomponent方法后面的代码文件中,将listbox的itemsource属性设置为MyObjects的列表。例如 MyListBox.ItemSource = listMyObjects
猜你喜欢
  • 2021-12-25
  • 2014-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-23
  • 1970-01-01
  • 1970-01-01
  • 2014-04-30
相关资源
最近更新 更多