我有一个多选模式的列表框,我必须将所选项目添加到字符串数组中。 我想获取用户检查的所有帐户ID。如何获取用户选择的项目?
XML
<ListBox Background="Transparent" Canvas.Left="18" Canvas.Top="74" Height="183" Name="listBoxAccountType" SelectionChanged="listBoxAccountType_SelectionChanged" SelectionMode="Multiple" Width="390" Visibility="Collapsed">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="0,1,0,0" BorderBrush="#FFC1BCBC" Width="490">
<Grid Height="80">
<CheckBox IsChecked="{Binding IsChecked}" Checked="CheckBox_Checked" Margin="0,0,0,0" Unchecked="CheckBox_Unchecked" BorderBrush="Black" Background="#FF3BB9FF" />
<TextBlock FontSize="20" FontWeight="Bold" Foreground="Black" Margin="50,12,0,0" Name="tbSelectedAccountType" Text="{Binding}" />
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Account.cs
[DataContract]
public class Accounts
{
public Accounts() { }
public Accounts(int accid, int clid)
{
this.accountId = accid;
this.clientId = clid;
}
public bool IsChecked
{
get;
set;
}
// [DataMember(Name = "accountId")]
[DataMember]
public int accountId
{ get; set; }
//[DataMember(Name = "clientId")]
[DataMember]
public int clientId
{ get; set; }
}
xaml.cs
private void listBoxAccountType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listBoxAccountType.SelectedIndex >= 0)
{
canvasType.Visibility = Visibility.Collapsed;
canvas_Mask.Visibility = Visibility.Collapsed;
string text = "";
foreach (var item in listBoxAccountType.SelectedItems)
{
text += item.ToString() + " ";
}
Console.WriteLine(text);
textBoxAccounts.Text = objAccountsName[listBoxAccountType.SelectedIndex];
Accounts objAccounts = (Application.Current as App).m_objAccounts[listBoxAccountType.SelectedIndex];
strAccountId = objAccounts.accountId.ToString();
}
}
private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
ListBoxItem checkedItem = this.listBoxAccountType.ItemContainerGenerator.ContainerFromItem((sender as CheckBox).DataContext) as ListBoxItem;
if (checkedItem != null)
{
checkedItem.IsSelected = true;
}
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
ListBoxItem checkedItem = this.listBoxAccountType.ItemContainerGenerator.ContainerFromItem((sender as CheckBox).DataContext) as ListBoxItem;
if (checkedItem != null)
{
// Accounts obj = checkedItem.it;
checkedItem.IsSelected = false;
}
}
答案 0 :(得分:1)
抛弃自定义Checked
事件处理(即删除CheckBox_Checked
方法)。没有必要,因为您使用DataBinding作为Checked
属性。
要获取已检查的元素,只需从绑定数据源中过滤掉元素,其中IsChecked为真。
然而,通过看起来,你没有使用适当的数据绑定列表,我强烈建议你read up about that topic
为了过滤掉元素,LINQ是你最好的朋友:
var checkedItems = myItems.Where(i => i.Checked == true)