I have a list box of multiple selection mode and i have to get the selected items to a string array. I want to get all the account ids that checked by the user. How can i get the items selected by the user?
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 listBoxAc开发者_如何学运维countType_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;
}
}
Ditch your custom Checked
event handling (ie. remove the CheckBox_Checked
method). It's not necessary, since you use DataBinding for the Checked
property.
To get the checked elements, simply filter the elements out from your bound datasource, where IsChecked is true.
However, by the looks if it, you aren't using proper databindings for the list, and I would strongly suggest you read up about that topic
For filtering out the elements, LINQ is your best friend:
var checkedItems = myItems.Where(i => i.Checked == true)
精彩评论