簡體   English   中英

如何訪問數據網格中的單元格? (wpf, c#)

[英]how to access cell in datagrid? (wpf, c#)

我試圖在單擊時獲取數據網格單元格的值。 單擊時如何獲取每個數據網格單元格的值?

例如,我想獲取 Name 變量的值(在 User 類中)單元格被單擊

請幫助我,我已經苦苦掙扎了幾個月...

我制作了一個 wpf 應用程序,可以通過單擊顯示對應於 treeview 項目的數據網格內容。

我想知道如何在單擊數據網格中的單元格時獲取每個單元格的值。

我的代碼的xaml datagrid里面沒有代碼,不知道怎么辦。

<UserControl x:Class="VSIXProject4.ToolWindow1Control"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:vsshell="clr-namespace:Microsoft.VisualStudio.Shell;assembly=Microsoft.VisualStudio.Shell.15.0"
         Background="{DynamicResource {x:Static vsshell:VsBrushes.WindowKey}}"
         Foreground="{DynamicResource {x:Static vsshell:VsBrushes.WindowTextKey}}"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300"
         Name="MyToolWindow">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <Grid>
        <TreeView>
            <TreeViewItem Header="TEST1">
                <TreeViewItem Header="TEST1_ITEM"
                              MouseDoubleClick="TEST1_CLICKED"></TreeViewItem>
            </TreeViewItem>
            <TreeViewItem Header="TEST2">
                <TreeViewItem Header="TEST2_ITEM"
                              MouseDoubleClick="TEST2_CLICKED"></TreeViewItem>
            </TreeViewItem>
            <TreeViewItem Header="TEST3">
                <TreeViewItem Header="TTEST3_ITEM"
                              MouseDoubleClick="TEST3_CLICKED"></TreeViewItem>
            </TreeViewItem>
        </TreeView>

    </Grid>

    <Grid Grid.Column="1">
        <DataGrid x:Name ="Test_grid" >
            
        </DataGrid>
    </Grid>

</Grid>
**namespace VSIXProject4
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.Windows;
    using System.Windows.Controls;

    /// <summary>
    /// Interaction logic for ToolWindow1Control.
    /// </summary>
    public partial class ToolWindow1Control : UserControl
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ToolWindow1Control"/> class.
        /// </summary>
        public ToolWindow1Control()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Handles click on the button by displaying a message box.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event args.</param>
        [SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions", Justification = "Sample code")]
        [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Default event handler naming pattern")]
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(
                string.Format(System.Globalization.CultureInfo.CurrentUICulture, "Invoked '{0}'", this.ToString()),
                "ToolWindow1");
        }

        private void TEST1_CLICKED(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            List<User> users = new List<User>();

            users.Add(new User() { Id = 1, Name = "A1", Birthday = new DateTime(1971, 7, 23) });

            users.Add(new User() { Id = 2, Name = "A2", Birthday = new DateTime(1974, 1, 17) });

            users.Add(new User() { Id = 3, Name = "A3", Birthday = new DateTime(1991, 9, 2) });

            Test_grid.ItemsSource = users;
        }

        public class User

        {

            public int Id { get; set; }

            public string Name { get; set; }

            public DateTime Birthday { get; set; }

        }

        public class User2

        {

            public int var_1 { get; set; }

            public string var_2 { get; set; }

            public string var_3 { get; set; }

        }

        private void TEST2_CLICKED(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            List<User2> users2 = new List<User2>();

            users2.Add(new User2() { var_1 = 1, var_2 = "A1", var_3 = "hi" });

            users2.Add(new User2() { var_1 = 2, var_2 = "A2", var_3 = "hello" });

            users2.Add(new User2() { var_1 = 3, var_2 = "A3", var_3 = "world" });

            Test_grid.ItemsSource = users2;
        }

        private void TEST3_CLICKED(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {

            List<User3> users3 = new List<User3>();

            users3.Add(new User3() { var_4 = 2341, var_5 = "aa", var_6 = "testtest" });

            users3.Add(new User3() { var_4 = 223, var_5 = "A2asd", var_6 = "helaaaalo" });

            users3.Add(new User3() { var_4 = 322, var_5 = "A3ff", var_6 = "worlfsddd" });

            Test_grid.ItemsSource = users3;
        }


        public class User3

        {

            public int var_4 { get; set; }

            public string var_5 { get; set; }

            public string var_6 { get; set; }

        }
    }


}

要在所選單元格更改時收到通知,請訂閱 Datagrid 的SelectedCellsChanged事件。

在 Datagrid 上設置SelectionUnit="Cell"SelectionMode="Single"屬性可確保用戶一次只能 select 一個單元格。

要從User獲取Name屬性,您可以執行以下操作:

    private void Test_grid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        IList<DataGridCellInfo> dataGridCells = Test_grid.SelectedCells; //Holds all currently selected cells.
        DataGridCellInfo selectedCell = dataGridCells.FirstOrDefault(); //Gets the first cell in that list.
        object item = selectedCell.Item; //Gets the Item object from the cell. 

        //Here we are using pattern matching to see if 'item' is a User object. 
        if (item is User user)
        {
            string username = user.Name; //Gets the Name property from the user property
            //Do something with the name here!
        }
    }

Go 在這里了解更多關於is關鍵字的信息。

注意:DataGridCellInfo.Item 將始終返回整個 object 而不僅僅是“綁定”到它的屬性。 這就是為什么我要測試 Item 是否是用戶而不是字符串!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM