【发布时间】:2017-09-01 20:17:08
【问题描述】:
我正在开发 WPF 应用程序,我有用户,当然用户有某种角色,在我的例子中是 SUPERADMIN 和 ADMIN,这些角色存储在表“Roles”中,
一个用户可以有 1 个或多个角色,这意味着可以在我的表单上选择一个或多个复选框(来自 ListBox)。
我应该在这里做什么:从数据库中获取所有角色,以便我以后可以为某些用户添加它们,我就是这样做的:
try
{
var activeRoles = RolesController.SelectAll();
if (activeRoles.Count > 0)
{
foreach(Role r in activeRoles)
{
listBox.Items.Add(r);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
listBox 是我的 ListBox,用于显示 DB 中的角色
XAML 显示:
<ListBox Grid.Row="8" Grid.Column="1" Margin="0,5,5,0" Name="listBox" FontSize="15" >
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Title}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
现在在 db 中我有 2 个角色,当我运行应用程序时,它会显示在 UI 上(标有绿色矩形):
但我现在想知道,如果我想为某些用户保存角色,这意味着我需要选择我想要保存的角色,我做到了
foreach (var item in listBox.SelectedItems)
{
//Do something...
}
listBox 始终是 Count:0,我发现我需要选择整个“行”才能使 selectedItems 工作,只有选择复选框实际上不能正常工作:/
这是怎么发生的,我该如何解决这些问题?
【问题讨论】:
-
@mm8 这是我的朋友 :)
标签: c# wpf xaml data-binding listbox