列表框,未获取所选项目

时间:2021-07-11 05:54:13

标签: c# listbox

我有一个 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 始终为 null。

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

这是如何修复的。

非常感谢

1 个答案:

答案 0 :(得分: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>


相关问题