尝试获取选定的行项目。 我一直认为它应该有效:
<DataGrid ItemsSource="{Binding Path=Customers}"
SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
Customer customer = (Customer)myDataGrid.SelectedItem;
在第一个xaml中 - 我说它,它没有错误或我不知道如何使用它的东西..如何在c#代码中我可以获得所选行?
在C#行代码中出错。视觉工作室并不存在客户。
我会感谢你的帮助。 :)谢谢。
答案 0 :(得分:0)
网格定义非常不完整。 理事会明确所有用个人约束构成的列
在这种情况下,我使用事件doubleClick,但您必须为您选择正确的事件
以代码为例,试试这个:
在XAML中添加:
<DataGrid x:Name="MyDataGrid" x:FieldModifier="public" MouseDoubleClick="MyDataGrid_MouseDoubleClick" ItemsSource="{Binding Path=Customers}"
SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
在c#后面编写代码:
private void MyDataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (sender != null)
{
DataGrid grid = sender as DataGrid;
if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
{
var selectedRow = grid.SelectedItem as MyObject;
try
{
Mouse.OverrideCursor = Cursors.Wait;
//TODO YOUR OPERATION ON selectdRow
}
finally
{
Mouse.OverrideCursor = null;
}
}
}
}
答案 1 :(得分:0)
<强>的Xaml 强>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" Name="dg"/>
<Button Grid.Row="1" Name="btn" Click="btn_Click" />
</Grid>
<强>代码隐藏强>
List<SomeInfo> list = new List<SomeInfo>();
public MainWindow()
{
InitializeComponent();
list.Add(new SomeInfo() { Name = "PC", Description = "Computer", ID = 1 });
list.Add(new SomeInfo() { Name = "PS", Description = "Playstation", ID = 2 });
list.Add(new SomeInfo() { Name = "XB", Description = "Xbox", ID = 3 });
this.dg.ItemsSource = list;
}
public class SomeInfo
{
public string Name { get; set; }
public string Description { get; set; }
public int ID { get; set; }
}
private void btn_Click(object sender, RoutedEventArgs e)
{
if (dg.SelectedIndex != -1)
{
DataGrid dataGrid = sender as DataGrid;
DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(dg.SelectedIndex);
DataGridCell RowColumn = dg.Columns[0].GetCellContent(row).Parent as DataGridCell;
btn.Content = ((TextBlock)RowColumn.Content).Text;
}
}
btn_click执行所有收集信息,其中最后2个使我的数据网格进行测试。
希望它会帮助你:))
<强> ------------------编辑------------------------- - 强>
从以下评论中您只需要
private void btn_Click(object sender, RoutedEventArgs e)
{
if (dg.SelectedIndex != -1)
{
DataGrid dataGrid = sender as DataGrid;
DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(dg.SelectedIndex);
DataGridCell RowColumn = dg.Columns[0].GetCellContent(row).Parent as DataGridCell;
btn.Content = ((TextBlock)RowColumn.Content).Text;
}
}
dg = your datagrid
dg.Columns[0] = change 0 into what column you want
info from btn.Content = what you want the content to be
--------------编辑2 ------------ 要获得所选行的所有索引,只需
int index = dg.SelectedIndex;
btn.Content = index;
或者如果您不想存储整合
btn.Content = dg.SelectedIndex;