如何检查按钮单击事件中的所有行中是否选中了WPF datagrid复选框 [英] How to check WPF datagrid checkbox is selected or not in all rows in button click event
问题描述
下面的例子在web应用程序中如何在wpf datagrid中写这样的内容
我尝试过:
$ / $
foreach(gdvResponsibility.Rows中的GridViewRow博士)
{
Action = 0;
CheckBox chkEdit =(CheckBox)Dr.FindControl(chkEdit);
CheckBox chkView =(CheckBox)Dr.FindControl(chkView);
Edit = Convert.ToInt16(gdvResponsibility.DataKeys [Dr.RowIndex] .Values [2] .ToString());
View = Convert.ToInt16(gdvResponsibility.DataKeys [Dr.RowIndex] .Values [3] .ToString());
if(chkEdit.Visible == false&& chkView.Checked == true)
Action = 2;
else if(chkEdit.Checked == false&& chkView.Checked == true)
Action = 2;
else if(chkEdit.Checked == true&& chkView.Checked == true)
Action = 3;
else if(chkEdit.Checked == true&& chkView.Checked == false)
Action = 1;
else if(chkEdit.Checked == false&& chkView.Checked == false)
Action = 0;
sQry [i ++] =INSERT INTO usermenu_mapping(UserId,MenuId,Action)VALUES('+ ddlUser.SelectedValue +',+ gdvResponsibility.DataKeys [Dr.RowIndex] .Values [0 ] .ToString()+,+ Action +)ON DUPLICATE KEY UPDATE Action =+ Action;
}
WPF相对于WinForms的功能在很多方面,其中一个是数据绑定 [ ^ ]。一旦你掌握了数据绑定,你就不会想直接使用控件,因为它更简单。
所以考虑到这一点,下面是一个演示如何解决方案的解决方案使用数据。
WPF数据绑定在数据更改时使用通知系统。对于单个对象/类,使用INotifyPropertyChanged
接口进行定义。为了简化实现,我使用以下基类:
public 摘要 类 ObservableBase:INotifyPropertyChanged
{
public void 设置< TValue>(参考 TValue字段,TValue newValue,
[CallerMemberName] string propertyName = )
{
if (EqualityComparer< TValue> .Default
.Equals(field, default (TValue))||
!field.Equals(newValue))
{
field = newValue;
PropertyChanged?.Invoke( this , new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged ;
}
1.首先我们需要对数据建模:
public class UserMenuMapping:ObservableBase
{
private long userId;
public long UserId
{
获取 = > userId;
set = > 设置( ref userId, value );
}
private int menuId;
public int MenuId
{
get = > menuId;
set = > 设置( ref menuId, value );
}
private bool canEdit;
public bool CanEdit
{
get = > canEdit;
set = > 设置( ref canEdit, value );
}
private bool canView;
public bool CanView
{
获取 = > canView;
set = > 设置( ref canView, value );
}
public int 行动()
{
if (!CanEdit&& CanView) return 2 跨度>;
else if (CanEdit&& CanView)返回 3 ;
其他 如果(CanEdit&&!CanView)返回 1 ;
return 0 ;
}
}
2.现在我们需要在我们的代码中设置数据。
对于对象集合,WPF有一个特殊的List集合类,名为ObservableCollection
,它实现了INotifyCollectionChanged
&安培;INotifyPropertyChanged
WPF数据绑定的接口。
public MainWindow()
{
InitializeComponent();
DataContext = this ; // 绑定到后面的代码
MockData(); // 加载要显示的数据
}
< span class =code-keyword> private void MockData()
{
Data.Clear(); // 始终使用clear而不是new来不破坏绑定
for ( int i = 0 ; i < 10 ; i ++)
{
Data.Add( new UserMenuMapping
{
UserId = 10000 + i,
MenuId = 10 + i,
CanEdit = true ,
CanView = true
});
}
}
public ObservableCollection< UserMenuMapping>数据{获取; }
= new ObservableCollection< UserMenuMapping>();
private void Button_Click(对象发件人,RoutedEventArgs e)
{
foreach ( var 数据中的行
{
// 保存到DB
Debug.WriteLine(
User:{row.UserId} | Menu:{row.MenuId} | Action:{row.Action()});
}
}
}
上面我们将XAML绑定到后面的代码。这会将Data
集合属性暴露给UI。现在我们可以绑定DataGrid
以允许编辑数据:
< 网格 >
< Grid.RowDefinitions >
< RowDefinition / >
< RowDefinition 高度 = 自动 / >
< / Grid。 RowDefinitions >
< DataGrid ItemsSource = {Binding Data}
GridLinesVisibility = 无
AlternatingRowBackground = GhostWhite AlternationCount = 1
ScrollViewer.HorizontalScrollBarVisibility = 隐藏
AutoGenerateColumns = False
< span class =code-attribute> RowDetailsVisibilityMode = VisibleWhenSelected
VirtualizingPanel.ScrollUnit = Pixel >
< DataGrid.Columns >
< DataGridTextColumn 标题 = 用户ID 绑定 = {绑定UserI d} / >
< DataGridTextColumn 标题 = 菜单ID < span class =code-attribute> Binding = {Binding MenuId} < span class =code-keyword> / >
< DataGridCheckBoxColumn 标题 = 可编辑 绑定 = {Binding CanEdit} / >
< span class =code-keyword>< DataGridCheckBoxColumn 标题 = 可以查看 绑定 = {绑定CanView } / >
< / DataGrid.Columns >
< / DataGrid >
< 按钮 内容 = SAVE Grid.Row = 1
点击 = Button_Click
< span class =code-attribute> HorizontalAlignment = 中心
填充 = 10 5 保证金 = 10 / >
< / Grid >
正如您在Button_Click
中所看到的那样,您无需做任何想要读回任何内容的事情。变化。
below example in web application how to write like this in wpf datagrid
What I have tried:
foreach (GridViewRow Dr in gdvResponsibility.Rows) { Action = 0; CheckBox chkEdit = (CheckBox)Dr.FindControl("chkEdit"); CheckBox chkView = (CheckBox)Dr.FindControl("chkView"); Edit = Convert.ToInt16(gdvResponsibility.DataKeys[Dr.RowIndex].Values[2].ToString()); View = Convert.ToInt16(gdvResponsibility.DataKeys[Dr.RowIndex].Values[3].ToString()); if (chkEdit.Visible == false && chkView.Checked == true) Action = 2; else if (chkEdit.Checked == false && chkView.Checked == true) Action = 2; else if (chkEdit.Checked == true && chkView.Checked == true) Action = 3; else if (chkEdit.Checked == true && chkView.Checked == false) Action = 1; else if (chkEdit.Checked == false && chkView.Checked == false) Action = 0; sQry[i++] = " INSERT INTO usermenu_mapping (UserId,MenuId,Action)VALUES('" + ddlUser.SelectedValue + "'," + gdvResponsibility.DataKeys[Dr.RowIndex].Values[0].ToString() + "," + Action + " ) ON DUPLICATE KEY UPDATE Action=" + Action; }
The power of WPF over WinForms is in a number of areas, one of those is Data Binding[^]. Once you master databinding you won't want to work directly with controls as it is far far simpler.
So with that in mind, Below is a solution that demonstrates how to work with the data.
WPF Data binding uses a notification system for when data changes. For individual objects/classes, is defind with theINotifyPropertyChanged
interface. To simplify the implementation, I use the following base class:
public abstract class ObservableBase : INotifyPropertyChanged { public void Set<TValue>(ref TValue field, TValue newValue, [CallerMemberName] string propertyName = "") { if (EqualityComparer<TValue>.Default .Equals(field, default(TValue)) || !field.Equals(newValue)) { field = newValue; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public event PropertyChangedEventHandler PropertyChanged; }
1. First we need to model the data:
public class UserMenuMapping : ObservableBase { private long userId; public long UserId { get => userId; set => Set(ref userId, value); } private int menuId; public int MenuId { get => menuId; set => Set(ref menuId, value); } private bool canEdit; public bool CanEdit { get => canEdit; set => Set(ref canEdit, value); } private bool canView; public bool CanView { get => canView; set => Set(ref canView, value); } public int Action() { if (!CanEdit && CanView) return 2; else if (CanEdit && CanView) return 3; else if (CanEdit && !CanView) return 1; return 0; } }
2. Now we need to set up the data in our code behind.
For Collections of objects, WPF has a special List collection class calledObservableCollection
which implements theINotifyCollectionChanged
&INotifyPropertyChanged
interfaces for WPF data binding.
public MainWindow() { InitializeComponent(); DataContext = this; // bind to code behind MockData(); // Load the data to be displayed } private void MockData() { Data.Clear(); // always use clear not new to not break the binding for (int i = 0; i < 10; i++) { Data.Add(new UserMenuMapping { UserId = 10000 + i, MenuId = 10+i, CanEdit = true, CanView = true }); } } public ObservableCollection<UserMenuMapping> Data { get; } = new ObservableCollection<UserMenuMapping>(); private void Button_Click(object sender, RoutedEventArgs e) { foreach (var row in Data) { // Save to DB Debug.WriteLine(
"User:{row.UserId} | Menu:{row.MenuId} | Action: {row.Action()}"); } } }
Above we bind the XAML to the code behind. This will expose theData
collection property to the UI. Now we can bind theDataGrid
to allow the data to be edited:
<Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <DataGrid ItemsSource="{Binding Data}" GridLinesVisibility="None" AlternatingRowBackground="GhostWhite" AlternationCount="1" ScrollViewer.HorizontalScrollBarVisibility="Hidden" AutoGenerateColumns="False" RowDetailsVisibilityMode="VisibleWhenSelected" VirtualizingPanel.ScrollUnit="Pixel"> <DataGrid.Columns> <DataGridTextColumn Header="User ID" Binding="{Binding UserId}"/> <DataGridTextColumn Header="Menu ID" Binding="{Binding MenuId}"/> <DataGridCheckBoxColumn Header="Can Edit" Binding="{Binding CanEdit}"/> <DataGridCheckBoxColumn Header="Can View" Binding="{Binding CanView}"/> </DataGrid.Columns> </DataGrid> <Button Content="SAVE" Grid.Row="1" Click="Button_Click" HorizontalAlignment="Center" Padding="10 5" Margin="10"/> </Grid>
As you can see in theButton_Click
you don't have to do anything fancy to read back any of the changes.
这篇关于如何检查按钮单击事件中的所有行中是否选中了WPF datagrid复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!