开发者

WPF ListBox binding when IsSynchronizedWithCurrentItem=true

开发者 https://www.devze.com 2023-03-16 13:21 出处:网络
<ListBox HorizontalAlignment=\"Right\" ItemsSource=\"{Binding Groups}\" SelectedValue=\"{Binding SelectedGroup}\"/>
<ListBox HorizontalAlignment="Right" 
   ItemsSource="{Binding Groups}" 
   SelectedValue="{Binding SelectedGroup}"/>

On startup, before the screen displayed, my viewmodel had SelectedGroup = Groups.First() (and Groups contained several items).

I spent about an hour trying to figure out why my item was not being selected. When I clicked (or pressed spacebar), then the selected item appeared selected, but before that, t开发者_如何学Gohe item did not appear selected.

After I added <ListBox IsSynchronizedWithCurrentItem ="True">, the app started working.

Question: Can someone explain why this is necessary? In other words, why would Microsoft have even made this an option? Wouldn't I always want this behavior?


Consider this example: Example

While using a ComboBox, it illustrates the idea: You don't want the first item automatically selected.


It turns out that my actual problem was that my application was generating a different list of Groups each time the property was accessed, and so the value SelectedGroup property never equaled a value in the Groups property.

Groups was implemented with an iterator like this:

public IEnumerable<Group> Groups
{
   get
   {
      yield return new Group {Name="Todo"};
      yield return new Group {Name="Done"};
   }
}
0

精彩评论

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

关注公众号