WPF 数据编辑器集合与列表框控件集成
在WPF应用程序开发中,数据编辑器和列表框控件的结合是常见需求。通过合理设计,可以实现高效的数据展示和编辑功能。以下内容将详细介绍如何实现这一功能。
数据模型与集合绑定
创建数据模型是基础步骤。定义一个简单的Person类作为数据项:
public class Person : INotifyPropertyChanged
{
private string _name;
private int _age;
public string Name
{
get => _name;
set { _name = value; OnPropertyChanged(); }
}
public int Age
{
get => _age;
set { _age = value; OnPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
创建可观察集合用于绑定到列表框:
public ObservableCollection<Person> People { get; } = new ObservableCollection<Person>();
列表框基础实现
XAML中定义列表框并绑定数据集合:
<ListBox x:Name="PeopleListBox"
ItemsSource="{Binding People}"
SelectedItem="{Binding SelectedPerson}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Width="150"/>
<TextBlock Text="{Binding Age}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
添加数据编辑功能
实现编辑功能需要添加数据输入控件。在列表框下方添加编辑面板:
<StackPanel DataContext="{Binding SelectedPerson}">
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"
Margin="5"/>
<TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}"
Margin="5"/>
</StackPanel>
命令实现与按钮操作
添加命令来控制数据操作:
public ICommand AddCommand { get;

被折叠的 条评论
为什么被折叠?



