WPF如何访问网格中的标签?

时间:2018-02-14 17:18:41

标签: c# wpf wpfgrid

我在代码网格中创建项目。

Border panel = new Border();
Grid.SetColumn(panel, 3);
Grid.SetRow(panel, 3);

StackPanel stack = new StackPanel();
panel.Child = stack;

Label hasta = new Label();
hasta.Content = str_hasta;
stack.Children.Add(hasta);


Label hastalik = new Label();
hastalik.Content = str_hastalik;
stack.Children.Add(hastalik);

grd_gunluk.Children.Add(panel);

单击此网格单元格时,我想获取标签文本。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

我想,你期待这个,

public MainWindow()
        {
            InitializeComponent();
            Border panel = new Border();
            Grid.SetColumn(panel, 3);
            Grid.SetRow(panel, 3);

            StackPanel stack = new StackPanel();
            panel.Child = stack;

            Label hasta = new Label();
            hasta.Content = "Test";
            hasta.PreviewMouseLeftButtonDown += PreviewMouseLeftButtonDownEvent;
            stack.Children.Add(hasta);


            Label hastalik = new Label();
            hastalik.Content = "MM";
            hastalik.PreviewMouseLeftButtonDown += PreviewMouseLeftButtonDownEvent;
            stack.Children.Add(hastalik);

            Grid.Children.Add(panel);
        }

        protected void PreviewMouseLeftButtonDownEvent(object sender, EventArgs e)
        {
            MessageBox.Show(((Label)sender).Content.ToString());
        }

获取标签框值的“堆栈”面板单击事件很复杂。因此,使用模型

使用数据网格和绑定

UI页面

<DataGrid Name="DataGrid" IsReadOnly="True" >
            <DataGrid.ItemContainerStyle>
                <Style TargetType="DataGridRow">
                    <EventSetter Event="MouseDoubleClick" Handler="Row_DoubleClick"/>
                </Style>
            </DataGrid.ItemContainerStyle>
        </DataGrid>

代码页

  public MainWindow()
    {
        InitializeComponent();
        List<Student> stud = new List<Student> {
    new Student {RollNo = 1, Name = "Ankur", marks = 34 },
    new Student {RollNo = 2, Name = "Dhrumit", marks = 79},
    new Student {RollNo = 3, Name = "Mannan", marks = 67 }};
        DataGrid.ItemsSource = stud;
    }

    public class Student
    {
        public int RollNo { get; set; }
        public string Name { get; set; }
        public double marks { get; set; }
    }   

    private void Row_DoubleClick(object sender, MouseButtonEventArgs e)
    {
        // execute some code
        var student = (Student)((System.Windows.Controls.DataGridRow)sender).Item;
        MessageBox.Show("RollNo = " + student.RollNo + " Name = " + student.marks + " marks = " + student.marks);
    }

用户界面图片

<强> UI Image

答案 1 :(得分:0)

您可以处理MouseLeftButtonDown的{​​{1}}事件:

Border