我使用一个名为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;
}
}
}