开发者

Binding not working Checked List BoX

开发者 https://www.devze.com 2023-02-12 00:49 出处:网络
Hi I have made checked List Box in WPF but the bind开发者_运维问答ing is not working correctly.I checked the List i created it contains the data in correct Format but when i bind it with the List box

Hi I have made checked List Box in WPF but the bind开发者_运维问答ing is not working correctly.I checked the List i created it contains the data in correct Format but when i bind it with the List box it does not work

only Last entry appears in list box number of item times that are in List

Checked Box List XML

<ListBox x:Name="list" Margin="18,100,535,74">
   <ListBox.ItemTemplate>
      <HierarchicalDataTemplate>
        <my:RibbonCheckBox Label="{Binding Name}" IsChecked="{Binding IsChecked}"  />                        
      </HierarchicalDataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Class For data holding

public class CheckedListItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsChecked { get; set; }
    }

Button to Populate List Box

private void button1_Click(object sender, RoutedEventArgs e)
{
  List<CheckedListItem> AvailablePresentationObjects = new List<CheckedListItem>();
  CheckedListItem item = new CheckedListItem();
  for (int i = 0; i < 10; i++)
  {
    item.Id = i;
    item.Name = i.ToString();
    item.IsChecked = false;
    AvailablePresentationObjects.Add(item);
  }
  list.ItemsSource = AvailablePresentationObjects;
}


You instantiate your CheckedListItem item = new CheckedListItem(); outside of the for loop, and only initialize one instance of CheckedListItem which you edit 10 times. Only the last edit remains.

You also added this very same instance, 10 times to the AvailablePresentationObjects.

Try the following:

  for (int i = 0; i < 10; i++)
  {
    CheckedListItem item = new CheckedListItem();
    item.Id = i;
    item.Name = i.ToString();
    item.IsChecked = false;
    AvailablePresentationObjects.Add(item);
  }


You're only creating one CheckedListItem and then running through each of the i's changing that single CheckedListItem you need to loop through the CheckedListItems in List applying the relevant i to each one.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号