为了避免你的代码隐藏方法,你应该使用 MVVM 模式MVVM Model View ViewModel 。一个可能的解决方案可能是这样的“人”(充当模型):
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
您可以实现一个 ViewModel,使用 ObservableCollection 的 Persons 初始化一个属性。
public class ViewModel
{
public ObservableCollection<Person> Persons { get; set; }
public ViewModel()
{
Persons = new ObservableCollection<Person>();
}
}
您的 MainWindow.cs 现在必须初始化 ViewModel:
public partial class MainWindow : Window
{
public ViewModel ViewModel;
public MainWindow()
{
ViewModel = new ViewModel();
ViewModel.Persons.Add(new Person
{
Age = 29,
Name = "Mustermann"
});
ViewModel.Persons.Add(new Person
{
Age = 35,
Name = "Meyer"
});
this.DataContext = ViewModel;
InitializeComponent();
}
将 DataContext 设置为 ViewModel 对象很重要。我添加了一个按钮和添加人员的方法。
private void AddPersonOnClick(object sender, RoutedEventArgs e)
{
ViewModel.Persons.Add(new Person
{
Age = 55,
Name = "Sand"
});
}
现在您可以在 XAML 中实例化 CollectionViewSource 并将其绑定到 ViewModel 中的 Persons ObservableCollection 属性。
<Window x:Class="DataGridStackoverflow.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">
<Window.Resources>
<CollectionViewSource x:Key="PersonsCollectionViewSource" Source="{Binding Persons}" />
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" ItemsSource="{Binding Source={StaticResource PersonsCollectionViewSource}}" />
<Button x:Name="AddPerson" Grid.Row="1" Click="AddPersonOnClick" HorizontalAlignment="Left">Add Person</Button>
</Grid>
最后,您必须在将 ItemsSource 发布到 CollectionViewSource 时设置它,它的工作原理就像一个魅力。
编辑
我尝试了您的解决方案,它也可以正常工作。 MainWindow.xaml:
<Window.Resources>
<dataGridStackoverflow:Persons x:Key="Persons" />
<CollectionViewSource x:Key="PersonsCollectionViewSource" Source="{StaticResource Persons}" />
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" ItemsSource="{Binding Source={StaticResource PersonsCollectionViewSource}}" />
<Button x:Name="AddPerson" Grid.Row="1" Click="AddPersonOnClick" HorizontalAlignment="Left">Add Person</Button>
</Grid>
在 InitializeComponent() 之后初始化 Persons 集合很重要。主窗口.cs
InitializeComponent();
Persons persons = (Persons)this.FindResource("Persons");
persons.Add(new Person
{
Age = 23,
Name = "Dude"
});
此解决方案无需使用代码隐藏构造来设置 ItemsSource。