【问题标题】:Listbox, not getting selected item列表框,没有得到选定的项目
【发布时间】:2021-07-11 05:54:13
【问题描述】:

我有一个 WPF 表单,上面有一个列表框和一个按钮。

我用 List 填充一个列表框(标签框),然后将其与数据源绑定,如下所示。

private void WeekFood_Load(object sender, EventArgs e)
        {
         List<string> tags = new List<string>() { "A", "B", "C"};
         tagbox.DataSource = tags;
         InitializeComponent();
        }

然后当我点击按钮时,我运行以下代码

 private void GenSunday_Click(object sender, EventArgs e)
        {
            MessageBox.Show(tagbox.SelectedItems.Count.ToString());            
        }

无论在列表框中选择了多少项,它总是返回 0,而 tagbox.SelectedItems 总是为空。

我尝试通过使用 valuemember 和 displaymember 迭代列表来填充框,但这也不能解决问题。

如何解决。

在此先感谢

【问题讨论】:

  • 请分享您的列表框的 wpf 代码。

标签: c# listbox


【解决方案1】:

在 WPF 中,请使用 ListBox 的 ItemSource 属性并将对象绑定到它。

也调用 InitializeComponent();在将任何数据分配给控件之前。

//MainWindow.xaml.cs

        public MainWindow()
        {
            InitializeComponent();

            List<string> tags = new List<string>() { "A", "B", "C" };
            tagBox.ItemsSource = tags;
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(tagBox.SelectedItems.Count.ToString());
        }

在 MainWindow.xaml 中


<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListBox x:Name="tagBox" HorizontalAlignment="Left" Height="100" Margin="99,249,0,0" VerticalAlignment="Top" Width="561"/>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="99,57,0,0" VerticalAlignment="Top" Width="148" Height="34" Click="button_Click"/>

    </Grid>
</Window>


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-12
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    相关资源
    最近更新 更多