简体   繁体   English

来自c#WPF应用程序中DataGrid的值,使用复选框

[英]Values from DataGrid in c# WPF Application using checkbox

I have a WPF Application and have populated a DataGrid with values from a SQL query. 我有一个WPF应用程序,并使用SQL查询中的值填充了DataGrid。 I have added a DataGridCheckBoxColumn and button to the window. 我已经在窗口中添加了DataGridCheckBoxColumn和按钮。 When the button is clicked I want to grab the data from the first selected row and insert into a text box or store as a variable. 单击按钮后,我想从第一行中获取数据并插入文本框或存储为变量。 Please explain the answer in a way that someone who is new to c# developing would understand so I can learn rather than copy and paste. 请以一种新接触c#的人可以理解的方式解释答案,以便我可以学习而不是复制和粘贴。

Here is my XAML: 这是我的XAML:

  <Window x:Class="WpfApplication7.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="NAME SELECT" 
    SizeToContent="WidthAndHeight"
    >
<Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <DataGrid x:Name="selectDataGrid" HorizontalAlignment="Left" VerticalAlignment="Top" Height="92" Width="288" AutoGenerateColumns="False">
        <Style  TargetType="{x:Type DataGridRow}" >

        </Style>
        <DataGrid.Columns>
            <DataGridCheckBoxColumn x:Name="dgCheckBox" Header="Select" Width="45" Binding="{Binding IsChecked}"/>
            <DataGridTextColumn Header="FIRST NAME" Width="125" Binding="{Binding FNAME}"/>
            <DataGridTextColumn Header="LAST NAME" Width="125" Binding="{Binding LNAME}"/>
        </DataGrid.Columns>


    </DataGrid>
    <Button Content="Update Fields" HorizontalAlignment="Left" Margin="193,97,0,0" VerticalAlignment="Top" Width="95" Click="Button_Click"/>

</Grid>

Here is my c# behind: 这是我的C#背后:

          private void Button_Click(object sender, RoutedEventArgs e)
    {
        for (int i = 0; i < selectDataGrid.Items.Count -1; i++) 
        {
            DataGridRow cell = GetRow(i);
            CheckBox tb = cell.value as CheckBox;
            System.Windows.MessageBox.Show(tb.IsChecked.ToString());
        }

    }
          public DataGridRow GetRow(int index)
    {
        DataGridRow row = (DataGridRow)selectDataGrid.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null)
        {
            selectDataGrid.UpdateLayout();
            selectDataGrid.ScrollIntoView(selectDataGrid.Items[index]);
            row = (DataGridRow)selectDataGrid.ItemContainerGenerator.ContainerFromIndex(index);
        }
        return row;
    }

If I could get help to the point of displaying the selected result to a message box I could go from there. 如果我可以在将所选结果显示到消息框时获得帮助,则可以从那里进行。 I'm only interested in the FIRST instance of a selected row. 我只对所选行的FIRST实例感兴趣。 So if multiple rows are selected I'm only interested in the first row selected. 因此,如果选择了多行,我只会对所选的第一行感兴趣。

I have read all the solutions to anything that had my keywords and I cannot find anything that fits my specific need of only wanting the first row. 我已经阅读了所有具有关键字的内容的所有解决方案,但找不到适合我仅需要第一行的特定需求的任何内容。 I'm not experienced enough to be able to make leaps and jumps or to alter code for something else to work for me. 我没有足够的经验来跳跃和改变代码以使其他东西对我有用。 If you are going to link me to another solution please explain what I would need to change on my code, or what parts I would need from the solution. 如果您要将我链接到另一个解决方案,请说明我需要对代码进行哪些更改,或者需要从解决方案中获取哪些部分。 Ideally working code in a solution is what would be best. 理想情况下,最好在解决方案中工作代码。

I can suggest you the next solution; 我可以建议您下一个解决方案; data grid has readonly dependency property (link to dependency property: msdn explanation and WPF Dependency Property , CodeProject explanation ) which cannot be accessed from XAML but you can access this in code behind or behavior code (link to behavior: good behavior explanation and anothere one good explanation ). 数据网格具有只读的依赖项属性(链接到依赖项属性: msdn说明WPF依赖项属性CodeProject说明 ),无法从XAML访问该属性 ,但是您可以在后面的代码或行为代码中访问此属性(行为的链接: 良好行为的解释另一个)很好的解释 )。 If you access this property and get the first member in that collection you will have the first selected item in your hands. 如果您访问此属性并获得该集合中的第一个成员,则您将拥有第一个选定的项目。 But I frankly advice you to learn the MVVM (link to MVVM: CodeProject explanation and more ) pattern. 但坦率地说,我建议您学习MVVM(指向MVVM的链接: CodeProject的说明更多内容 )模式。 The MVVM pattern is the a correct way to work with the WPF. MVVM模式是使用WPF的正确方法。 Solution: 1. XAML code: 解决方案:1. XAML代码:

<Window x:Class="SimpleDataGrid.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:simpleDataGrid="clr-namespace:SimpleDataGrid"
    Title="MainWindow" Height="350" Width="525">
<Grid >
    <Grid.RowDefinitions>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.DataContext>
        <simpleDataGrid:GridViewModel/>
    </Grid.DataContext>
    <DataGrid x:Name="SelectDataGrid" ItemsSource="{Binding Persons}" HorizontalAlignment="Left" VerticalAlignment="Top" AutoGenerateColumns="False">
       <DataGrid.Resources>
            <Style  TargetType="{x:Type DataGridRow}" >

            </Style>
        </DataGrid.Resources>
        <DataGrid.Columns>
            <DataGridCheckBoxColumn x:Name="dgCheckBox" Header="Select" Width="45" Binding="{Binding IsChecked}"/>
            <DataGridTextColumn Header="FIRST NAME" Width="125" Binding="{Binding FNAME}"/>
            <DataGridTextColumn Header="LAST NAME" Width="125" Binding="{Binding LNAME}"/>
        </DataGrid.Columns>
    </DataGrid>
    <Button Grid.Row="1" Content="Update Fields" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top" Width="95" Click="Button_Click"/>

</Grid></Window>

2. View Model code: 2.查看型号代码:

    public class GridViewModel:BaseObservableObject
{
    public GridViewModel()
    {
        var l = new List<Person>
        {
            new Person {FNAME = "John", LNAME = "W"},
            new Person {FNAME = "George", LNAME = "R"},
            new Person {FNAME = "Jimmy", LNAME = "B"},
            new Person {FNAME = "Marry", LNAME = "B"},
            new Person {FNAME = "Ayalot", LNAME = "A"},
        };
        Persons = new ObservableCollection<Person>(l);
    }

    public ObservableCollection<Person> Persons { get; set; }
}

3. Code behind and Person model: 3.后面的代码和Person模型:

    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var dataGrid = SelectDataGrid;
        var selected = dataGrid.SelectedItems.Cast<Person>().ToList();
        var mostFirst = selected.FirstOrDefault();
    }
}


public class Person : BaseObservableObject
{
    private string _lName;
    private string _fName;
    private bool _checked;

    public bool IsChecked
    {
        get { return _checked; }
        set
        {
            _checked = value;
            OnPropertyChanged();
        }
    }

    public string LNAME
    {
        get { return _lName; }
        set
        {
            _lName = value;
            OnPropertyChanged();
        }
    }

    public string FNAME
    {
        get { return _fName; }
        set
        {
            _fName = value;
            OnPropertyChanged();
        }
    }
}

4. BaseObservableObject code (simple implementation of INotifyPropertyChanged): 4. BaseObservableObject代码(INotifyPropertyChanged的简单实现):

  public class BaseObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    protected virtual void OnPropertyChanged<T>(Expression<Func<T>> raiser)
    {
        var propName = ((MemberExpression)raiser.Body).Member.Name;
        OnPropertyChanged(propName);
    }

    protected bool Set<T>(ref T field, T value, [CallerMemberName] string name = null)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            OnPropertyChanged(name);
            return true;
        }
        return false;
    }
}

I hope it will help you. 希望对您有帮助。 Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM