我有两个相同的datagrids
(datagrid1
,datagrid2
),我想将datagridrow
从已填充的datagrid1
拖到相同的datagrid2
,但我没有快乐,dragdrop
似乎工作,我可以看到我在调试时选择的行,但当我将其放入datagrid2
时,它会添加一个没有数据的空行?我认为drop事件中的代码是错误的,但我无法看到。任何人都可以帮我填空吗?
感谢您一如既往的帮助。
这是我的代码
namespace DataGridDragNDrop
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Persons persons = new Persons();
List<Persons> list = new List<Persons>()
{
new Persons(){ Name="Brian", Province="Aberdeenshire", City="Ellon", Age=55 },
new Persons(){ Name="Stuart", Province="Dumbartonshire", City="Dumbarton", Age=27 },
new Persons(){ Name="Harry", Province="Wiltshire", City="Wimborne", Age=31 }
};
datagrid1.DataContext = list;
}
private void datagrid1_MouseMove(object sender, MouseEventArgs e)
{
if(e.LeftButton == MouseButtonState.Pressed)
{
Persons person = (Persons)datagrid1.SelectedItem;
DataObject dragData = new DataObject("dragData", person);
DragDrop.DoDragDrop(datagrid1, dragData, DragDropEffects.Move);
}
}
private void datagrid2_DragEnter(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.Move;
}
private void datagrid2_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("dragData"))
{
Persons person = e.Data.GetData("dragData") as Persons;
DataGrid datagrid2 = sender as DataGrid;
datagrid2.Items.Add(person.Name + person.City + person.Province + person.Age);
}
}
}
}
XAML
<Grid>
<DataGrid Name="datagrid1" AutoGenerateColumns="False" ItemsSource="{Binding}" CanUserAddRows="False" Margin="109,58,149,0" Height="105" VerticalAlignment="Top" IsReadOnly="True" MouseMove="datagrid1_MouseMove">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"></DataGridTextColumn>
<DataGridTextColumn Header="County" Binding="{Binding Province}"></DataGridTextColumn>
<DataGridTextColumn Header="City" Binding="{Binding City}" Width="*"></DataGridTextColumn>
<DataGridTextColumn Header="Age" Binding="{Binding Age}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<DataGrid Name="datagrid2" AutoGenerateColumns="False" CanUserAddRows="True" AllowDrop="True" Margin="109,183,149,25" IsReadOnly="True" DragEnter="datagrid2_DragEnter" Drop="datagrid2_Drop">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"></DataGridTextColumn>
<DataGridTextColumn Header="County" Binding="{Binding Province}"></DataGridTextColumn>
<DataGridTextColumn Header="City" Binding="{Binding City}" Width="*"></DataGridTextColumn>
<DataGridTextColumn Header="Age" Binding="{Binding Age}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
答案 0 :(得分:0)
更改
datagrid2.Items.Add(person.Name + person.City + person.Province + person.Age);
到
datagrid2.Items.Add(person);
P.S。:未经测试,但a + b + c + d看起来很可疑。