【问题标题】:Values from DataGrid in c# WPF Application using checkbox使用复选框在 c# WPF 应用程序中来自 DataGrid 的值
【发布时间】:2015-11-10 03:56:42
【问题描述】:

我有一个 WPF 应用程序,并使用 SQL 查询中的值填充了一个 DataGrid。我在窗口中添加了一个 DataGridCheckBoxColumn 和按钮。单击按钮时,我想从第一个选定行中获取数据并插入文本框或存储为变量。请以不熟悉 c# 开发的人能够理解的方式解释答案,以便我可以学习而不是复制和粘贴。

这是我的 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>

下面是我的 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;
    }

如果我能获得帮助,将所选结果显示到消息框,我可以从那里开始。我只对选定行的第一个实例感兴趣。因此,如果选择了多行,我只对选择的第一行感兴趣。

我已经阅读了包含我的关键字的任何内容的所有解决方案,但我找不到任何符合我只想要第一行的特定需求的内容。我没有足够的经验来进行跳跃或更改代码以使其他东西为我工作。如果您要将我链接到另一个解决方案,请解释我需要对我的代码进行哪些更改,或者我需要从解决方案中获得哪些部分。理想情况下,解决方案中的工作代码是最好的。

【问题讨论】:

  • 首先,您可以将 DataGrid 配置为只允许单行选择,不是吗?
  • @user3486773 您好,在按钮单击处理程序中使用代码的工作解决方案对您有好处吗?

标签: c# wpf checkbox datagrid


【解决方案1】:

我可以建议你下一个解决方案;数据网格具有只读依赖属性(链接到依赖属性:msdn explanationWPF Dependency PropertyCodeProject explanation)无法从 XAML 访问,但您可以在代码隐藏或行为代码中访问它(链接到行为:good behavior explanationanothere one good explanation)。如果您访问此属性并获得该集合中的第一个成员,您将拥有第一个选定的项目。但我坦率地建议你学习 MVVM(链接到 MVVM:CodeProject explanationmore)模式。 MVVM 模式是使用 WPF 的正确方法。解决方案: 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。查看模型代码:

    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。代码隐藏和 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 代码(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;
    }
}

希望对你有所帮助。 问候。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 2018-06-24
    • 1970-01-01
    相关资源
    最近更新 更多