Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 列表框并查找所选复选框_C#_Wpf_Checkbox_Listbox - Fatal编程技术网

C# 列表框并查找所选复选框

C# 列表框并查找所选复选框,c#,wpf,checkbox,listbox,C#,Wpf,Checkbox,Listbox,我目前正在从事一个C#wpf项目。我有一个列表框,我用下面的代码动态地向列表框添加复选框 while (reader.Read()) { Console.WriteLine("Database: " + reader.GetString("Database")); string databaseName = reader.GetString("Database"); CheckBox chkDatabase = new CheckBox(); chkDat

我目前正在从事一个C#wpf项目。我有一个列表框,我用下面的代码动态地向列表框添加复选框

while (reader.Read())
{
     Console.WriteLine("Database: " + reader.GetString("Database"));
     string databaseName = reader.GetString("Database");
     CheckBox chkDatabase = new CheckBox();
     chkDatabase.Content = databaseName.Replace("_", "__");
     chkDatabase.Uid = "chk_" + reader.GetString("Database");
     chkDatabase.Checked += new RoutedEventHandler(chkDatabase_Checked);

     lstDatabase.Items.Add(chkDatabase);
}
这可以正常工作,routedeventhandler可以正常工作,以确定是否选中了复选框

我希望能够做到的是允许用户单击复选框所在的行,而不是实际检查该行。我在列表框中添加了一个事件处理程序,用于更改如下所示的选择:

private void lstDatabase_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Console.WriteLine("Selection Changed");
    ListBox checkbox = (ListBox)e.Source;
    Console.WriteLine("Checkbox2: " + checkbox.SelectedValue);
}
如何从selection changed事件处理程序中获取复选框值


谢谢你能提供的帮助

要获取复选框本身,我们只需将所选项目(这将是一个复选框,因为您只向列表框的项目添加了复选框)强制转换为复选框

CheckBox chkBox = lstDatabase.SelectedItem as CheckBox;
然后,我们只需使用

chkBox.IsChecked;
将该代码放入SelectionChanged函数中,您将检索复选框值。你也可以把它设置在那里

我希望这有帮助

编辑:


但是,我建议在不同的事件上运行此代码。如果用户单击已选择的项目以切换复选框,则不会触发SelectionChanged事件。我建议使用MouseUp,前提是在运行代码之前测试是否确实存在selectedItem。

一种简单的方法是:

ListBoxItem lbItem = new ListBoxItem();
lbItem.Content = chkDatabase;
lstDatabase.Items.Add(lbItem);
然后在处理程序中:

bool chkVal = false;
ListBoxItem selItem = lstDatabase.SelectedItem as ListBoxItem;
if (selItem != null && selItem.Content is CheckBox)
    chkVal = ((CheckBox)selItem.Content).IsChecked;

解决这个问题的一种方法是切换到数据绑定

创建一个类(我们称之为a)(它实现了INotifyPropertyChanged),该类表示列表框中的单个项,并向名为Selected的类添加一个属性

创建ObservableCollection的实例(我们将其命名为col),并为每行/每项添加一个实例

现在按如下方式绑定列表框:

代码中的第一个
lstDatabase.DataContext=col

然后在XAML中:

<ListBox ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我有三个文本块和列表框内的复选框作为数据模板内的数据绑定。如何检查复选框是否选中。。。上面的代码在chkbox处返回null…请参阅helpo。。
var selectedItems = col.Where(item => item.IsSelected);