如何使用Datagrid.SelectedItem
以编程方式选择行?
我是否首先必须创建IEnumerable
个DataGridRow
个对象并将匹配的行传递给此SelectedItem
属性,或者我该如何处理?
修改
在选择行之前,我需要首先将第一列单元格的单元格内容与TextBox.Text
匹配。
答案 0 :(得分:36)
请检查以下代码是否适合您;它遍历datagris第一列的单元格,并检查单元格内容是否等于textbox.text值并选择该行。
for (int i = 0; i < dataGrid.Items.Count; i++)
{
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
TextBlock cellContent = dataGrid.Columns[0].GetCellContent(row) as TextBlock;
if (cellContent != null && cellContent.Text.Equals(textBox1.Text))
{
object item = dataGrid.Items[i];
dataGrid.SelectedItem = item;
dataGrid.ScrollIntoView(item);
row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
break;
}
}
希望这有帮助,尊重
答案 1 :(得分:21)
您无需遍历DataGrid
行,您可以通过更简单的解决方案实现目标。
为了匹配您的行,您可以遍历绑定到DataGrid.ItemsSource
属性的集合,然后以编程方式将此项目分配给DataGrid.SelectedItem
属性,或者您可以将其添加到DataGrid.SelectedItems
集合中如果要允许用户选择多行。请参阅以下代码:
<Window x:Class="ProgGridSelection.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" Loaded="OnWindowLoaded">
<StackPanel>
<DataGrid Name="empDataGrid" ItemsSource="{Binding}" Height="200"/>
<TextBox Name="empNameTextBox"/>
<Button Content="Click" Click="OnSelectionButtonClick" />
</StackPanel>
public partial class MainWindow : Window
{
public class Employee
{
public string Code { get; set; }
public string Name { get; set; }
}
private ObservableCollection<Employee> _empCollection;
public MainWindow()
{
InitializeComponent();
}
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
// Generate test data
_empCollection =
new ObservableCollection<Employee>
{
new Employee {Code = "E001", Name = "Mohammed A. Fadil"},
new Employee {Code = "E013", Name = "Ahmed Yousif"},
new Employee {Code = "E431", Name = "Jasmin Kamal"},
};
/* Set the Window.DataContext, alternatively you can set your
* DataGrid DataContext property to the employees collection.
* on the other hand, you you have to bind your DataGrid
* DataContext property to the DataContext (see the XAML code)
*/
DataContext = _empCollection;
}
private void OnSelectionButtonClick(object sender, RoutedEventArgs e)
{
/* select the employee that his name matches the
* name on the TextBox
*/
var emp = (from i in _empCollection
where i.Name == empNameTextBox.Text.Trim()
select i).FirstOrDefault();
/* Now, to set the selected item on the DataGrid you just need
* assign the matched employee to your DataGrid SeletedItem
* property, alternatively you can add it to your DataGrid
* SelectedItems collection if you want to allow the user
* to select more than one row, e.g.:
* empDataGrid.SelectedItems.Add(emp);
*/
if (emp != null)
empDataGrid.SelectedItem = emp;
}
}
答案 2 :(得分:8)
我搜索过类似问题的解决方案,也许我的方式会帮助你和任何面对它的人。
我在XAML DataGrid定义中使用了SelectedValuePath="id"
,并且我只需要将DataGrid.SelectedValue
设置为所需的值。
我知道这个解决方案有利有弊,但在具体情况下是快速而简单的。
祝你好运
的Marcin
答案 3 :(得分:7)
做你想做的事比我想要的要复杂一点,但那是因为你并没有真正直接将DataGrid
绑定到DataTable
。
将DataGrid.ItemsSource
绑定到DataTable
时,您确实将其绑定到默认DataView
,而不是绑定到表本身。这就是为什么,例如,当您单击列标题时,您不必执行任何操作来创建DataGrid
排序行 - 该功能已烘焙到DataView
,DataGrid
知道如何访问它(通过IBindingList
接口)。
DataView
实现IEnumerable<DataRowView>
(或多或少),DataGrid
通过迭代来填充其项目。这意味着当您将DataGrid.ItemsSource
绑定到DataTable
时,其SelectedItem
属性将为DataRowView
,而不是DataRow
。
如果您了解所有这些,那么构建一个包装类非常简单,它允许您公开可以绑定的属性。有三个关键属性:
Table
,DataTable
,Row
,类型为DataRowView
的双向可绑定属性,SearchText
,一个字符串属性,当它被设置时,将在表的默认视图中找到第一个匹配的DataRowView
,设置Row
属性,并引发PropertyChanged
看起来像这样:
public class DataTableWrapper : INotifyPropertyChanged
{
private DataRowView _Row;
private string _SearchText;
public DataTableWrapper()
{
// using a parameterless constructor lets you create it directly in XAML
DataTable t = new DataTable();
t.Columns.Add("id", typeof (int));
t.Columns.Add("text", typeof (string));
// let's acquire some sample data
t.Rows.Add(new object[] { 1, "Tower"});
t.Rows.Add(new object[] { 2, "Luxor" });
t.Rows.Add(new object[] { 3, "American" });
t.Rows.Add(new object[] { 4, "Festival" });
t.Rows.Add(new object[] { 5, "Worldwide" });
t.Rows.Add(new object[] { 6, "Continental" });
t.Rows.Add(new object[] { 7, "Imperial" });
Table = t;
}
// you should have this defined as a code snippet if you work with WPF
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
{
h(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
// SelectedItem gets bound to this two-way
public DataRowView Row
{
get { return _Row; }
set
{
if (_Row != value)
{
_Row = value;
OnPropertyChanged("Row");
}
}
}
// the search TextBox is bound two-way to this
public string SearchText
{
get { return _SearchText; }
set
{
if (_SearchText != value)
{
_SearchText = value;
Row = Table.DefaultView.OfType<DataRowView>()
.Where(x => x.Row.Field<string>("text").Contains(_SearchText))
.FirstOrDefault();
}
}
}
public DataTable Table { get; private set; }
}
这是使用它的XAML:
<Window x:Class="DataGridSelectionDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
xmlns:DataGridSelectionDemo="clr-namespace:DataGridSelectionDemo"
Title="DataGrid selection demo"
Height="350"
Width="525">
<Window.DataContext>
<DataGridSelectionDemo:DataTableWrapper />
</Window.DataContext>
<DockPanel>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label>Text</Label>
<TextBox Grid.Column="1"
Text="{Binding SearchText, Mode=TwoWay}" />
</Grid>
<dg:DataGrid DockPanel.Dock="Top"
ItemsSource="{Binding Table}"
SelectedItem="{Binding Row, Mode=TwoWay}" />
</DockPanel>
</Window>
答案 4 :(得分:2)
//一般来说,访问所有行//
foreach (var item in dataGrid1.Items)
{
string str = ((DataRowView)dataGrid1.Items[1]).Row["ColumnName"].ToString();
}
//访问选定的行//
private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
string str = ((DataRowView)dataGrid1.SelectedItem).Row["ColumnName"].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
答案 5 :(得分:1)
我已经更改了serge_gubenko的代码并且效果更好
for (int i = 0; i < dataGrid.Items.Count; i++)
{
string txt = searchTxt.Text;
dataGrid.ScrollIntoView(dataGrid.Items[i]);
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
TextBlock cellContent = dataGrid.Columns[1].GetCellContent(row) as TextBlock;
if (cellContent != null && cellContent.Text.ToLower().Equals(txt.ToLower()))
{
object item = dataGrid.Items[i];
dataGrid.SelectedItem = item;
dataGrid.ScrollIntoView(item);
row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
break;
}
}
答案 6 :(得分:0)
我最近遇到过这个问题(与问题的年龄相比)TechNet文章,其中包含了我可以在该主题上找到的一些最佳技术:
WPF: Programmatically Selecting and Focusing a Row or Cell in a DataGrid
它包含应涵盖大多数要求的详细信息。重要的是要记住,如果为某些行指定DataGridRow的自定义模板,这些行不会包含DataGridCells,那么网格的正常选择机制将不起作用。
正如其他人所说的那样,您需要更具体地说明您给出网格的数据源以回答问题的第一部分。
答案 7 :(得分:0)
如果有任何人在这里遇到问题,在OnSelectionChanged之后发生内部网格选择问题 - 在尝试所有选择设置器十几个小时失败之后,唯一有用的是重新加载和重新填充DataGrid以及所选项目。根本不优雅,但此时我不确定在我的情况下是否存在更好的解决方案。
datagrid.ItemsSource = null
datagrid.ItemsSource = items;
datagrid.SelectedItem = selectedItem;