Having a weird problem that I've not been able to solve. I have a gridview that has a button to edit a list of roles for a user, which gets displayed in a child window. That window has a listbox bound to a ria query. Everything works fine the first time the childwindow is displayed. But when opening it more than once, the listbox's items collection is empty, so the checkboxes aren't set properly. Why is the items collection empty?
xaml:
<ListBox Name="lstRoles" HorizontalAlignment="Left" Height="406" Margin="10,10,0,0" VerticalAlignment="Top" Width="372" Loaded="lstRoles_Loaded_1" ItemsSource="{Binding Data, ElementName=rolesQueryDomainDataSource, Mode=OneWay}" ScrollViewer.VerticalScrollBarVisibility="Visible">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Name="spRoles">
<CheckBox x:Name="chkRoleSelected" Unchecked="chkRoleSelected_Unchecked_1" Checked="chkRoleSelected_Checked_1"/>
<TextBlock x:Name="txtRoleId" Visibility="Collapsed" Text="{Binding RoleId}"/>
<TextBlock Text="{Binding Description}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Codebehind:
private void FillListBox(ListBox lb)
{
MembershipContext context = new MembershipContext();
EntityQuery<aspnet_UsersInRoles> query = from c in context.GetAspnet_UsersInRolesQuery() where c.UserId == _crmContact.UserId select c;
var loadOp = context.Load(query);
loadOp.Completed += (opSender, eArgs) =>
{
var op = opSender as LoadOperation;
List<aspnet_UsersInRoles> rowData = ((LoadOperation<aspnet_UsersInRoles>)op).Entities.ToList();
var index = 0;
foreach (var item in lb.Items)
{
var role = item as RolesQuery;
var lbi = lb.ItemContainerGenerator.ContainerFromIndex(index) as ListBoxItem;
CheckBox chk = FindDescendant<CheckBox>(lbi);
var x = (from r in rowData where r.RoleId == role.RoleId select r).FirstOrDefault();
if (x != null)
{
chk.IsChecked = true;
}
index++;
}
};
}