ListBox获取、设置选中项用法

ListBox控件的SelectedItems表示当ListBox允许选中多行时,用户选中的所有选项。
SelectionMode=none表示无法选中,
SelectionMode=one表示可选中一行,
SelectionMode=MultiSimple表示可选中多行,
SelectionMode=MultiExtended表示可选中多行且能用shift、ctrl来选择
读取方法如下:

private void button1_Click(object sender, EventArgs e)
{
    List<string> list = new List<string>();
    for (int i = 0; i < listBox1.SelectedItems.Count; i++)
    {       
        list.Add(listBox1.SelectedItems[i].ToString());
    }
}

ListBox控件的SelectedItem表示当前控件所有选中项中的第一项,

string str = listBox1.SelectedItem.ToString();

ListBox控件的Text表示当前控件选中项中的内容,如果有多个选中项,则Text表示选中项中的第一项的内容,

string text = listBox1.Text.Trim();

当LixtBox控件中的值不为空时,默认选中第一个,如果想取消默认选中功能,可以使用Clear()方法,如果确定LixtBox控件中的值不为空时可以使用SetSelected(0,false),代码如下:

//【1】取消默认选中项
this.lbTables.SelectedItems.Clear();
//【2】取消默认选中项
//lbTables.SetSelected(0, false);
  • 8
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
如果您在WPF中使用了三层嵌套的ListBox,并且想要获取当前选中,您可以使用以下代码: ```csharp // 获取外层ListBox选中 var outerSelectedItem = outerListBox.SelectedItem; // 获取中间ListBox选中 var middleListBoxItem = (ListBoxItem)middleListBox.ItemContainerGenerator.ContainerFromItem(middleListBox.SelectedItem); var innerListBox = middleListBoxItem?.FindVisualChild<ListBox>(); var innerSelectedItem = innerListBox?.SelectedItem; ``` 在上面的代码中,我们首先获取外层ListBox选中,这是最简单的部分。接下来,我们使用中间ListBox的ItemContainerGenerator和ContainerFromItem方法来获取选中ListBoxItem。然后,我们查找其中的嵌套ListBox,并获取选中。请注意,我们使用了FindVisualChild扩展方法来查找嵌套ListBox,该方法在下面的代码中定义: ```csharp public static T FindVisualChild<T>(this DependencyObject parent) where T : DependencyObject { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) { var child = VisualTreeHelper.GetChild(parent, i); if (child != null && child is T) return (T)child; else { var result = FindVisualChild<T>(child); if (result != null) return result; } } return null; } ``` 此方法将递归地查找指定类型的子元素,并返回第一个找到的元素。在我们的示例中,我们使用此方法查找嵌套的ListBox。 请注意,FindVisualChild并不是WPF的标准方法,但是它对于查找嵌套元素非常有用,并且可以在需要的情况下使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

changuncle

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值