我的用户控件中有一个列表框,每当用户控件的数据上下文发生更改时,我想选择列表框中的第一项。 (列表框的 ItemsSource 绑定(bind)到 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 在填充列表框项目之前被触发,因为事件处理程序中的消息框将返回先前列表框项目的计数。 请帮我找到解决方案。 谢谢
最佳答案
试试这个
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;
}
如果在最后一行放置断点
listBox_Resources.ItemContainerGenerator.StatusChanged += eventHandler;
并在调试器中观察 listBox_Resources.ItemContainerGenerator.Status 的值,它应该显示为“ContainersGenerate”。如果您随后在委托(delegate) EventHanler 的
处添加断点if (listBox_Resources.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
您应该第一次看到“c_listBox.ItemContainerGenerator.Status = GeneratingContainers”,然后当它再次出现时,它应该是ContainersGenerate,然后我们可以设置SelectedIndex。不管怎样,这对我有用。
关于WPF 列表框 dataContextChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4096426/