ObservableCollection上的WPF数据绑定

时间:2016-06-10 07:14:09

标签: c# wpf xaml data-binding

我使用一个名为dog的类创建了一个简单的应用程序。在我的主窗口的代码隐藏文件中,我创建了public ObservableCollection<Dog> dogNameCollection = new ObservableCollection<Dog>();。课堂内Dog只是一个属性,名称。我想将属性名称绑定到数据网格。

我将此行添加到我的MainWindow.xaml.cs文件中: this.dgDogNames.DataContext = this.dogNameCollection;

DataGridTextColumn看起来像这样: <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*"/>

那我的错误在哪里?也许有人可以帮助我。

MainWindow.xaml

<Window x:Class="BindingTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <TextBox Name="txtBoxDogName" Margin="5" Padding="5"/>
    <Button Name="btnSetValue" Margin="5" Padding="5" Content="Set name" Click="btnSetValue_Click"/>

    <DataGrid Margin="5" Name="dgDogNames" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*"/>
        </DataGrid.Columns>
    </DataGrid>
</StackPanel>
</Window>

MainWindow.xaml.cs

namespace BindingTest
{
public partial class MainWindow : Window
{
    public ObservableCollection<Dog> dogNameCollection = new ObservableCollection<Dog>();

    public MainWindow()
    {
        InitializeComponent();
        this.dgDogNames.DataContext = this.dogNameCollection;
    }

    private void btnSetValue_Click(object sender, RoutedEventArgs e)
    {
        this.dogNameCollection.Add(new Dog(this.txtBoxDogName.Text));
    }
}
}

Dog.cs

namespace BindingTest
{
public class Dog
{
    private string _name;
    public string Name
    {
        get { return this._name; }
        set { this._name = value; }
    }

    public Dog(string name)
    {
        this.Name = name;
    }
}
}

0 个答案:

没有答案