SfDataGrid如何获取选中行数及右键菜单点击时判断选中行
解决SfDataGrid无选中行时上下文菜单操作崩溃及获取选中行数问题
一、检查是否有行被选中
在MenuFlyoutItem_Clicked方法开头,通过以下两种方式判断是否存在选中行(任选其一即可,推荐结合使用):
- 检查当前激活行是否为空:
if (PasswdVw.CurrentRow == null) - 检查选中行集合的数量:
if (PasswdVw.SelectedItems.Count == 0)
二、获取选中行数
直接通过SfDataGrid的SelectedItems.Count属性获取选中行数,无选中行时返回0,有选中行时返回对应数量:
int selectedRowCount = PasswdVw.SelectedItems.Count;
三、修改后的MenuFlyoutItem_Clicked事件代码
在代码开头加入判断逻辑,避免空引用崩溃,同时优化重复类型转换操作:
private void MenuFlyoutItem_Clicked(object sender, EventArgs e) { // 无选中行时直接返回,避免后续操作崩溃 if (PasswdVw.CurrentRow == null || PasswdVw.SelectedItems.Count == 0) { // 可选:添加用户提示,比如MessageBox.Show("请先选择一行数据"); return; } MenuFlyoutItem mnuItem = sender as MenuFlyoutItem; string takeAct = mnuItem.CommandParameter as string; PasswrdInfo selectedRow = PasswdVw.CurrentRow as PasswrdInfo; string url = selectedRow.PassUrl; string msg, retVal; msg = retVal = ""; int idno = selectedRow.PassId; switch (takeAct) { case "UsrName": using (SqlConnection c = new SqlConnection(App.ConnStr)) { string query = "select usrname from PassWrds where Id = " + idno; using (SqlCommand cmd = new SqlCommand(query, c)) { c.Open(); var queryResult = cmd.ExecuteScalar(); retVal = queryResult?.ToString() ?? ""; c.Close(); if (!string.IsNullOrEmpty(retVal)) { Clipboard.SetTextAsync(retVal); msg = "User Name copied."; } } } break; case "Passwd": using (SqlConnection c = new SqlConnection(App.ConnStr)) { string query = "select password from PassWrds where Id = " + idno; using (SqlCommand cmd = new SqlCommand(query, c)) { c.Open(); var queryResult = cmd.ExecuteScalar(); retVal = queryResult?.ToString() ?? ""; c.Close(); } if (!string.IsNullOrEmpty(retVal)) { string decryptedResult = Crypto.Decrypt(App.secretKey, retVal); Clipboard.SetTextAsync(decryptedResult); msg = "Password copied."; } } break; case "WebSite": //Nothing Yet. break; } }
额外优化:对数据库查询结果做null判断,避免查询为空时触发ToString()空引用异常。
四、进阶优化:上下文菜单显示前禁用无效项
可以在菜单打开前自动禁用菜单项,从源头避免无效操作:
- 给MenuFlyout添加
Opening事件 - 在事件中根据选中行数量控制菜单项启用状态:
private void MenuFlyout_Opening(object sender, object e) { bool hasSelectedRow = PasswdVw.SelectedItems.Count > 0; MenuFlyout flyout = sender as MenuFlyout; foreach (var item in flyout.Items) { if (item is MenuFlyoutItem menuItem) { menuItem.IsEnabled = hasSelectedRow; } } }
- 绑定到XAML的MenuFlyout上:
<FlyoutBase.ContextFlyout> <MenuFlyout Opening="MenuFlyout_Opening"> <MenuFlyoutItem Text="Copy User Name" Clicked="MenuFlyoutItem_Clicked" CommandParameter="UsrName"/> <MenuFlyoutItem Text="Copy Password" Clicked="MenuFlyoutItem_Clicked" CommandParameter="Passwd"/> <MenuFlyoutItem Text="Copy Web Site" Clicked="MenuFlyoutItem_Clicked" CommandParameter="WebSite"/> </MenuFlyout> </FlyoutBase.ContextFlyout>
内容的提问来源于stack exchange,提问作者user21591607
相关产品推荐
相关产品推荐

