How to add an item from one datagrid to another then edit it in WPF
当我尝试使用datagrid.items.add()将项目从一个datagrid添加到另一个datagrid时,我遇到了一个问题。基本上,我有两个数据网格在主从关系中起作用。第一个DataGrid1用于显示自动生成的列和行。第二个DataGrid,DataGrid2将在单击特定按钮时显示DataGrid1.SelectedItems。每次单击该按钮时,我都希望DataGrid1中的选定项保留在DataGrid2中,并且每次单击该按钮时,都会有更多项添加到DataGrid2中。除了能够编辑DataGrid2上的单元格外,我已经能够完成我的大部分需求。当我双击DataGrid2中的一个单元格时,我会得到一个异常,该异常表示此视图不允许使用"EditItem"。我读过很多关于向ObservableCollection、ListCollectionView等添加数据的文章,但是要么我不能以正确的方式实现它们,要么我的情况下没有工作。我的代码如下,顺便提一下THX
1 2 3 4 5 6 7 8 9 | <Window x:Class="WpfApplication1.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"> <Grid> <DataGrid AutoGenerateColumns="False" Height="77" HorizontalAlignment="Left" Margin="27,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="464" /> <Button Content="AddRow" Height="23" HorizontalAlignment="Left" Margin="27,107,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> <DataGrid AutoGenerateColumns="False" Height="140" HorizontalAlignment="Left" Margin="27,159,0,0" Name="dataGrid2" VerticalAlignment="Top" Width="464" /> </Grid> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication1 { /// /// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); dataGrid1.ItemsSource = idata; } private void button1_Click(object sender, RoutedEventArgs e) { foreach (latlongobj item in dataGrid1.SelectedItems) { dataGrid2.Items.Add(item); } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WpfApplication1 { class latlonobj { public string name { get; set; } public double Lat { get; set; } public double Lon { get; set; } } } |
这就是你想要的吗?
公共分部类主窗口:窗口{observableCollection datagrid2items=new observableCollection();
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public MainWindow() { InitializeComponent(); dataGrid1.ItemsSource = idata; dataGrid2.ItemsSource = dataGrid2Items; } private void button1_Click(object sender, RoutedEventArgs e) { foreach (latlongobj item in dataGrid1.SelectedItems) { if( !dataGrid2Items.Contains( item ) ) dataGrid2Items.Add(item); } } private ObservableCollection<latlongobj> idata = new ObservableCollection<latlongobj> { new latlongobj{ name ="n1", Lat = 1, Lon = 2 }, new latlongobj{ name ="n2", Lat = 2, Lon = 3 }, new latlongobj{ name ="n3", Lat = 4, Lon = 5 }, }; |