GridView绑定不起作用。我错过了什么?

时间:2015-08-08 01:54:24

标签: c# gridview binding

GridView Binding不起作用。你能看看我错过了什么吗? 为了您的方便,我发布了所有代码。 此测试代码的目的是,如果单击“添加”按钮,则会将人员类添加到gridview中。

下面的C#代码......

public partial class MainWindow : Window
{
    List<Person> persons;
    public MainWindow()
    {
        InitializeComponent();
        persons = new List<Person>() { new Person() {Name="A", Age=20},
                                        new Person() {Name="B", Age=30}};

        lstView.ItemsSource = persons;
    }

    private void Add_Click(object sender, RoutedEventArgs e)
    {
        persons.Add(new Person { Name = tbName.Text, Age = Int32.Parse(tbAge.Text) });
    }


}

public class Person : INotifyPropertyChanged
{
    private string name;
    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            OnPropertyChanged("Name");
        }
    }

    private int age;
    public int Age
    {
        get { return age; }
        set 
        { 
            age = value;
            OnPropertyChanged("Age");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

和xaml代码..

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Width="525" Height="150">

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50"/>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="30"/>
        <RowDefinition Height="30"/>
        <RowDefinition Height="30"/>
        <RowDefinition Height="30"/>
    </Grid.RowDefinitions>
    <TextBlock Grid.Column="0">Name</TextBlock>
    <TextBox Grid.Column="1" x:Name="tbName"></TextBox>
    <TextBlock Grid.Column="0" Grid.Row="1">Age</TextBlock>
    <TextBox Grid.Column="1" Grid.Row="1" x:Name="tbAge"></TextBox>
    <Button Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="2" Click="Add_Click"> Add </Button>
    <ListView Grid.Column="2" Grid.RowSpan="4" x:Name="lstView">
        <ListView.View>
            <GridView>
                <GridView.Columns>
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
                    <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}"/>
                </GridView.Columns>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

2 个答案:

答案 0 :(得分:1)

您需要ObservableCollection而不是List

 ObservableCollection<Person> persons;

答案 1 :(得分:1)

INotifyPropertyChanged用于对象的更改(在您的情况下为每个Person实例)。

您需要ObservableCollection(实现INotifyCollectionChanged)来监听集合中的更改(在您的情况下,集合中新的和已删除的Person实例)。

  

表示在何时提供通知的动态数据集合   项目被添加,删除或刷新整个列表。

更多信息here