在wpf应用程序中,我有标签,其中包含Dropdown。下拉列表包含不同的表。所有表都有不同的列。我想实现以下功能主义者,
1)根据下拉列表选择显示一个网格,其中包含所选表格的所有列。 2)向该表添加新行 3)编辑所选表的列
我是WPF的新手,如果有人能建议我应该采用什么样的方法,那将会非常棒?
答案 0 :(得分:1)
假设您正在使用MVVM: 1.将组合框selectedItem绑定到如下属性:
public int SelectedItem
{
get
{
return _selecteditem;
}
set
{
if (_selectedItem != value)
{
_selectedItem = value;
RaisePropertyChanged("SelectedItem");
UpdateGridData();
}
}
}
当选择更改时,将调用UpdateGridData方法。更新绑定到UpdateGridData方法中的数据网格ItemsSource的集合。
例如:让你的DataGrid绑定到一个名为MyCustomCollection的集合,该集合声明如下:
public ICollectionView MyCustomCollection
{
get;
set;
}
您的XAML将如下所示:
<DataGrid ItemsSource="{Binding MyCustomCollection}" .../>
在您的视图模型中,实现UpdateGridData(),如下所示:
void UpdateGridData()
{
//resultfromDatabase is the collection from which the data based on the selected item is added to
var resultDataFromDatabase = GetDataFromDatabase(this.SelectedItem);
MyCustomCollection = CollectionViewSource.GetDefaultView(resultDataFromDatabase);
}
要添加新行,只需调用要绑定到DataGrid ItemsSource的集合的源的Add()方法。您还应该查看datagrid的CanUserAddRows属性。
编辑数据网格时,只需网格可编辑,并在焦点更改时保存数据。或者,您可以在DataGrid中创建一个DataGridTemplateColumn,并在其中添加一个自定义编辑按钮,该按钮可以启用行的编辑或打开一个新的模态窗口,您可以在其中编辑字段并保存它。
希望这有帮助。
如果答案有帮助,请不要忘记投票,如果这回答了您的问题,请将其标记为答案。