【问题标题】:ListBox checklist SelectedItem returns nullListBox 清单 SelectedItem 返回 null
【发布时间】:2019-11-21 08:04:14
【问题描述】:

我想创建一个列表框,可以从中选择带有复选框的元素。它通过数据绑定从数据库中获取元素。这些项目出现在列表框中,但是当我发送表单时,代码隐藏没有收到 SelectedItem 值。

列表框的 XAML 部分如下所示:

<Grid x:Name="grMozik" Visibility="Visible" Margin="0,0,0,0" DataContext="{Binding}" Grid.Row="3" Grid.ColumnSpan="2">
    <ListBox Name="lbMozik" Margin="15" Width="300" Height="200" ItemsSource="{Binding}">
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Focusable" Value="False"/>
            </Style>
        </ListBox.ItemContainerStyle>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding MoziNeve}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

出于测试目的,显示所选项目的代码如下所示:

string text = ((ListBoxItem)lbMozik.SelectedItem).Content.ToString();
MessageBox.Show(text2);

【问题讨论】:

  • 创建并发布MCVE

标签: c# wpf data-binding


【解决方案1】:

ListBox.SelectedItem 来自 ListBoxItem,其中 IsSelected 属性设置为 true。如果要通过 CheckBoxes 进行选择,则将它们中的每一个绑定到所有者ListBoxItem.IsSelected

<CheckBox Content="{Binding MoziNeve}"
          IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}"/>

【讨论】:

  • ListBox.SelectedItem 不是ListBoxItem,它是一个数据对象,除了数据对象是ListBoxItem
  • @Rekshino,它也可以是 ListBoxItem(当 Items 集合被 ListBoxItems 填充时)
  • 正如我写的“除了数据对象是一个ListBoxItem”
猜你喜欢
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-08
  • 2017-05-21
  • 1970-01-01
相关资源
最近更新 更多