我正在开发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;
任何建议,
此致 桑杰塔
答案 0 :(得分:2)
在列表框中创建动态多项的方法不是代码隐藏,而是为项创建模板,然后将其绑定到项列表。
示例强>
说我有一堆段落List<Passage> Passages { get; set; }
:
public class Passage
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
在我的xaml中,我创建了一个模板并绑定到它
<ListBox ItemsSource="{Binding Passages}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" />
<TextBlock Text="{Binding Path=Name, StringFormat=Passage: {0}}"
Foreground="Blue" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
结果在我的四个段落中看起来像这样#34; Alpha&#34;,&#34; Beta&#34;,&#34; Gamma&#34;和&#34; I-25&#34;:
然后,如果我想要所选项目,例如上面最近检查的Beta
,我只列举所选项目的列表。
var selecteds = Passages.Where(ps => ps.IsSelected == true);
需要在一个ListBox中列出不同类型的对象吗?从绑定到复合集合或ObservableCollection<T>
说?
在这里查看我的答案: