简体   繁体   English

C#WPF DataTemplate绑定

[英]C# WPF DataTemplate binding

I bind MyListBox to a List of MyObject instances. 我将MyListBox绑定到MyObject实例列表。 MyObject contains a string field named TextField. MyObject包含一个名为TextField的字符串字段。 I want to bind every item in listBox to MyObject.TextField . 我想将listBox中的每个项目绑定到MyObject.TextField My code is the following, but it doesn't work. 我的代码如下,但是它不起作用。

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

What is the proper way to do that? 这样做的正确方法是什么?

Solved: TextField of My Object's class wasn't a property 解决:我的物件类别的TextField不是属性

Make sure to set the ListBox's ItemsSource : 确保设置ListBox的ItemsSource

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

EDIT: i tried the solution in VS 2010...here is the code 编辑:我尝试了VS 2010中的解决方案...这是代码

first you create your own class, for example person class 首先,您创建自己的班级,例如人班

class Person
{

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

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

then you create listbox in xaml like this 然后像这样在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>

note in xaml Path=Name is the property which you want to display in the listbox xaml中的note注释Path = Name是要在列表框中显示的属性

in the code behind file, enter the following code 在文件后面的代码中,输入以下代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM