WPF listBox dataContextChanged
I've a listbox in a userControl and I want to select the first item in the listbox whenever datacontext of my userControl is changed. (listbox's ItemsSource is Bind to开发者_如何转开发 userControl dataContext :
<userControl>
<ListBox Name="listBox_Resources" ItemsSource="{Binding Path=Resources}" DataContextChanged="listBox_Resources_DataContextChanged">
</ListBox>
</userControl>
private void listBox_Resources_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
MessageBox.Show(listBox_Resources.SelectedIndex.ToString() + " " + listBox_Resources.Items.Count.ToString());
listBox_Resources.SelectedIndex = 0;
}
it seems that dataContextChanged is fired before the listbox items is populated because my messagebox in the eventhandler will return me count of the previous listbox items. please help me finding the solution. thanks
Try this
private void listBox_Resources_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
EventHandler eventHandler = null;
eventHandler = new EventHandler(delegate
{
if (listBox_Resources.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
listBox_Resources.SelectedIndex = 0;
listBox_Resources.ItemContainerGenerator.StatusChanged -= eventHandler;
}
});
listBox_Resources.ItemContainerGenerator.StatusChanged += eventHandler;
}
If you put a breakpoint at the last line
listBox_Resources.ItemContainerGenerator.StatusChanged += eventHandler;
and watch the value of listBox_Resources.ItemContainerGenerator.Status in the debugger it will should read "ContainersGenerated". If you then add a breakpoint within the delegate EventHanler at
if (listBox_Resources.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
you should see that "c_listBox.ItemContainerGenerator.Status = GeneratingContainers" a first time and then when it hits again it should be ContainersGenerated and then we can set SelectedIndex. Anyway, that's working for me.
精彩评论