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 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;
}
}