Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
WPF数据网格设置选定行_Wpf_Select_Datagrid_Selecteditem - Fatal编程技术网

WPF数据网格设置选定行

WPF数据网格设置选定行,wpf,select,datagrid,selecteditem,Wpf,Select,Datagrid,Selecteditem,如何使用Datagrid.SelectedItem以编程方式选择行 我是否必须首先创建DataGridRow对象的IEnumerable,并将匹配的行传递给此SelectedItem属性,或者如何操作 编辑: 在选择行之前,我需要先将第一列单元格的单元格内容与TextBox.Text匹配 请检查下面的代码是否适合您;它遍历datagris第一列的单元格,检查单元格内容是否等于textbox.text值,并选择行 for (int i = 0; i < dataGrid.Items.Coun

如何使用
Datagrid.SelectedItem
以编程方式选择行

我是否必须首先创建
DataGridRow
对象的
IEnumerable
,并将匹配的行传递给此
SelectedItem
属性,或者如何操作

编辑:


在选择行之前,我需要先将第一列单元格的单元格内容与
TextBox.Text
匹配

请检查下面的代码是否适合您;它遍历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;
    }
}
for(int i=0;i

希望这有帮助,因为您不需要遍历
DataGrid
行,您可以使用更简单的解决方案实现您的目标。 为了匹配行,您可以遍历绑定到
数据网格的集合。ItemsSource
属性然后将此项分配给您
数据网格。以编程方式选择EdItem
属性,或者,您可以将其添加到
数据网格中。如果要允许用户选择多行,请选择editems
集合。请参阅下面的代码:

<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>

公共部分类主窗口:窗口
{
公营雇员
{
公共字符串代码{get;set;}
公共字符串名称{get;set;}
}
私人可观察收集(empu collection);;
公共主窗口()
{
初始化组件();
}
WindowLoaded上的私有void(对象发送方,RoutedEventArgs e)
{
//生成测试数据
_EMP收集=
新可观测集合
{
新员工{Code=“E001”,Name=“Mohammed A.Fadil”},
新员工{Code=“E013”,Name=“Ahmed Yousif”},
新员工{Code=“E431”,Name=“Jasmin Kamal”},
};
/*设置Window.DataContext,也可以设置
*将DataGrid DataContext属性添加到employees集合。
*另一方面,您必须绑定数据网格
*DataContext属性设置为DataContext(请参阅XAML代码)
*/
数据上下文=_empCollection;
}
private void on Selection按钮单击(对象发送方,路由目标)
{
/*选择与其姓名匹配的员工
*文本框上的名称
*/
var emp=(来自_emp集合中的i)
其中i.Name==empNameTextBox.Text.Trim()
选择i).FirstOrDefault();
/*现在,要在DataGrid上设置所选项目,只需
*将匹配的员工分配给DataGrid SeletedItem
*属性,也可以将其添加到DataGrid中
*如果要允许用户使用,请选择EditEMS集合
*要选择多行,例如:
*empDataGrid.SelectedItems.Add(emp);
*/
如果(emp!=null)
empDataGrid.SelectedItem=emp;
}
}

我已经找到了类似问题的解决方案,也许我的方法会帮助你和任何面对这个问题的人

我在XAML DataGrid定义中使用了
SelectedValuePath=“id”
,从编程角度来说,我唯一需要做的就是将
DataGrid.SelectedValue
设置为所需的值

我知道这个解决方案有优点和缺点,但在具体情况下是快速和简单的

致意


Marcin

做你想做的事情比我更喜欢做的事情有点棘手,但那是因为你没有真正直接将
数据网格
绑定到
数据表

DataGrid.ItemsSource
绑定到
DataTable
时,实际上是将其绑定到默认的
DataView
,而不是表本身。这就是为什么,例如,当您单击列标题时,您不必做任何事情来对行进行排序,
DataGrid
——该功能被烘焙到
DataView
,并且
DataGrid
知道如何访问它(通过
IBindingList
界面)

DataView
实现了
IEnumerable
(或多或少),而
DataGrid
则通过迭代来填充其项。这意味着当您将
DataGrid.ItemsSource
绑定到
DataTable
时,其
SelectedItem
属性将是
DataRowView
,而不是
DataRow

如果您了解所有这些,那么构建一个包装器类非常简单,它允许您公开可以绑定的属性。有三个关键属性:

  • 数据表
  • ,类型为
    DataRowView
    的双向可绑定属性,以及
  • SearchText
    ,一个字符串属性,设置该属性后,将在表的默认视图中找到第一个匹配的
    DataRowView
    ,设置
    属性,并引发
    属性更改
看起来是这样的:

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; }
}
公共类DataTableWrapper:INotifyPropertyChanged
{
私有数据行视图_行;
私有字符串_SearchText;
公共DataTableWrapper()
{
//使用无参数构造函数可以直接在XAML中创建它
DataTable t=新的DataTable();
t、 添加(“id”,typeof(int));
t、 添加(“文本”,类型(字符串));
//
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; }
}
<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>
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);
    }
}
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;
    }
}
datagrid.ItemsSource = null
datagrid.ItemsSource = items;
datagrid.SelectedItem = selectedItem;