【发布时间】:2015-10-20 19:18:10
【问题描述】:
我正在开发 WPF 应用程序。在其中,我通过以下方式将CheckBoxes 添加到ListBox。
foreach (User ls in lst)
{
AddContacts(ls, lstContactList);
}
private void AddContacts(User UserData, ListBox lstbox)
{
try
{
var txtMsgConversation = new CheckBox()
{
Padding = new Thickness(1),
IsEnabled = true,
//IsReadOnly = true,
Background = Brushes.Transparent,
Foreground = Brushes.White,
Width = 180,
Height = 30,
VerticalAlignment = VerticalAlignment.Top,
VerticalContentAlignment = VerticalAlignment.Top,
Content = UserData.Name, //+ "\n" + UserData.ContactNo,
Margin = new Thickness(10, 10, 10, 10)
};
var SpConversation = new StackPanel() { Orientation = Orientation.Horizontal };
SpConversation.Children.Add(txtMsgConversation);
var item = new ListBoxItem()
{
Content = SpConversation,
Uid = UserData.Id.ToString(CultureInfo.InvariantCulture),
Background = Brushes.Black,
Foreground = Brushes.White,
BorderThickness = new Thickness(1),
BorderBrush = Brushes.Gray
};
item.Tag = UserData;
lstbox.Items.Add(item);
}
catch (Exception ex)
{
//Need to log Exception
}
}
现在我需要从ListBox 获取选中的项目。我该如何继续,我尝试了下面的代码,它返回null,
CheckBox chkBox = lstContactList.SelectedItem as CheckBox;
想法?
【问题讨论】:
-
这不是您应该使用 WPF 的方式。阅读
DataBinding和MVVM的内容,否则你会做任何比要求更复杂的事情。 -
删除所有内容并使用正确的 XAML 和 DataBinding。
-
我设法得到使用下面的代码,foreach (ListBoxItem item in lstContactList.Items) { var stackPanel = item.Content as StackPanel; var checkBox = stackPanel.Children[0] as CheckBox;
-
创建文本框时,将事件处理程序添加到其选中的更改事件中。在该处理程序中,发件人将转换为一个复选框,您可以使用它来管理已检查项目的集合。这是一个指针而不是答案,因为 mvvm 会让这变得简单得多,你看看。背后的代码可以更快地证明一个想法,但在你的情况下 - 直接使用 mvvm。