代码之家  ›  专栏  ›  技术社区  ›  wonea Ilya Smagin

捕获WPF列表框复选框选择

  •  0
  • wonea Ilya Smagin  · 技术社区  · 16 年前

    我一直在想,如何从列表框中捕获事件。在模板中,我添加了参数ischecked=“”,它启动了我的方法。但是,问题是试图捕获方法中已签入的内容。SelectedItem只返回当前选定的内容,而不返回复选框。

    object selected = thelistbox.SelectedItem;
    DataRow row = ((DataRowView)selected).Row;
    string teststring = row.ItemArray[0].ToString();    // Doesn't return the checkbox!
    
    <ListBox IsSynchronizedWithCurrentItem="True" Name="thelistbox" ItemsSource="{Binding mybinding}">
        <ListBox.ItemTemplate>
                <DataTemplate>
                        <StackPanel>
                                <CheckBox Content="{Binding personname}" Checked="CheckBox_Checked" Name="thecheckbox"/>
                            </StackPanel>
                    </DataTemplate>
            </ListBox.ItemTemplate>
    </ListBox>
    
    1 回复  |  直到 16 年前
        1
  •  1
  •   repka    16 年前

    理想情况下,您应该将ischecked绑定到行中的属性,即

    <CheckBox Content="{Binding personname}" IsChecked="{Binding IsPersonChecked}" Name="thecheckbox"/>
    

    其中“ispersonchecked”是数据表中的列(或绑定到的任何列),就像“personname”。然后,您可以从数据行变量中直接读取是否检查它:

    DataRow row = ((DataRowView)thelistbox.SelectedValue).Row;
    bool isPersonChecked = (bool) row["IsPersonChecked"];
    

    显然,如果数据集是类型化的,那么您需要使用类型化的数据行属性。

    请注意,我使用的是SelectedValue,而不是SelectedItem属性。我相信SelectedItem实际上是ListBoxItem的一个实例。如果你想让Ischecked保持未绑定状态,可以使用它。然后,考虑到完整的模板层次结构,您必须检索复选框。类似:

    bool isChecked = ((CheckBox)((StackPanel) ((ListBoxItem) thelistbox.SelectedItem).Content).Children[0]).IsChecked ?? false;
    

    凌乱。(调试并调整层次结构,使其符合实际情况。我的代码可能无法正常工作。)

    更好的方法是使用复选框“选中处理程序”的RoutedEventargs:

    private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        CheckBox checkBox = (CheckBox) e.Source;
        DataRow row = ((DataRowView) checkBox.DataContext).Row;
        bool isChecked = checkBox.IsChecked ?? false;
    }
    
    推荐文章