WPF 列表框 dataContextChanged
我的用户控件中有一个列表框,每当用户控件的数据上下文发生更改时,我想选择列表框中的第一项。 (列表框的 ItemsSource 绑定到 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;
}
似乎 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试一下
如果您在最后一行放置断点
并在调试器中观察 listBox_Resources.ItemContainerGenerator.Status 的值,它应该显示为“ContainersGenerate”。如果您随后在委托 EventHanler 中添加一个断点,
您应该第一次看到“c_listBox.ItemContainerGenerator.Status = GeneratingContainers”,然后当它再次命中时,它应该是 ContainersGenerate,然后我们可以设置 SelectedIndex。无论如何,这对我有用。
Try this
If you put a breakpoint at the last line
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
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.