且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将等效的datagridview更改为wpf datagrid?

更新时间:2023-09-18 23:37:04

嗨会员,



此代码你显示的不是很安全 - 你说单元格[0]有索引,字符串比较等等。我希望你不要过分依赖这个索引的东西。



无论如何,我认为你有理由使用这些代码...



在WPF你通常会使用Binding将列表(一些枚举)绑定到 DataGrid 。所以我使用Linq在您的底层数据源中找到所需的记录(行),然后您可以使用 ItemCollection IndexOf 方法/ code>。



此代码显示了这个想法 - 如果您使用以下内容替换新WPF项目中的MainWindow,则可以运行它。



Hi Member,

This code you are showing is not very safe - you say the cell[0] has the index, string comparison etc. I hope you don't rely heavily on this "index" thing.

Anyway, I assume you have got reasons to use such code...

In WPF you would normally use Binding to bind a list (some enumeration whatever) to your DataGrid. So I'd use Linq to find the desired record (row) in your underlaying datasource, then you can just use the IndexOf method of the ItemCollection.

This code shows the idea - you can run it if you replace MainWindow in a new WPF project with the following.

<Window x:Class="WpfApplication2.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 x:Name="m_datagrid"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="422,283,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>

    </Grid>
</Window>




   public partial class MainWindow : Window
    {
        class Record
        {
            public string Key { get; set; }
            public string Value { get; set; }
        }

        List<Record> m_list = new List<Record> 
        {
            new Record { Key = "A", Value = "aaa"},
            new Record { Key = "B", Value = "bbb"},
            new Record { Key = "C", Value = "ccc"}
        };

        public MainWindow()
        {
            InitializeComponent();

            m_datagrid.ItemsSource = m_list;

        }

        int GetRowIndex(string strKey)
        {
            int iIndex = -1;

            // search the record given by the key (id) in the underlaying datasource (a simple List in this case)
            Record record = m_list.FirstOrDefault(r => r.Key == strKey);
            // get the index of the found record (or -1 if it wasn't found)
iIndex = m_datagrid.Items.IndexOf(record);

            return iIndex;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(this, GetRowIndex("C").ToString());

        }





只是我的2c - 也许它可以帮到你。



快乐编码!



Just my 2c - maybe it helps you.

Happy coding!