绑定的ItemsControl在显示之前没有更新
本文关键字:更新 显示 ItemsControl 绑定 | 更新日期: 2023-09-27 17:51:04
我有一个UserControl
,它由几个绑定的ItemsControl
和strings
组成,根据按下的按钮,显示不同的数据。下面是Button
的一个点击事件的示例:
private void LeftPreviousScoresButton_Click(object sender, RoutedEventArgs e)
{
if (m_previousScoresWindow.Visibility == Visibility.Visible)
{
m_previousScoresWindow.Hide();
}
else
{
WindowTitle = "Left Side";
PreviousScoresA = m_previousLeftWristErosionScoresReaderA;
PreviousScoresB = m_previousLeftWristErosionScoresReaderB;
m_previousScoresWindow.Show();
}
}
有几个这样的单击事件侦听器,它们为WindowTitle
、PreviousScoresA
和PreviousScoresB
分配相关的数据。然后UserControl
像这样绑定到它们:
<ItemsControl Height="Auto" Width="Auto"
ItemsSource="{Binding ElementName=ParentForm, Path=PreviousScoresA}"
Grid.Row="1" />
<ItemsControl Height="Auto" Width="Auto"
ItemsSource="{Binding ElementName=ParentForm, Path=PreviousScoresB}"
Grid.Row="2" />
<TextBlock FontSize="16" FontWeight="Bold" Height="25"
Margin="5" HorizontalAlignment="Center" Foreground="Black"
Text="{Binding ElementName=ParentForm, Path=PreviousScoresWindowTitle}" />
然而,当打开窗口时,旧数据在用当前数据更新之前会显示一秒钟。我甚至尝试在Window
上调用Hide()
时添加这些调用,但似乎没有帮助:
WindowTitle = String.Empty;
PreviousScoresA = new ObservableCollection<PreviousScoreData>();
PreviousScoresB = new ObservableCollection<PreviousScoreData>();
是否有任何方法可以确保Show()
直到绑定数据更新后才被调用?谢谢。
由于您使用的是ObservableCollection
,因此不应该重新初始化集合。相反,它应该被清除,然后添加新的值;这有助于在使用ObservableCollection
时保持集合同步。
根据你的代码样本,这是一个有点黑暗的镜头;如果您在隐藏时清除集合,然后用新值重新填充它们,那么您应该得到所需的效果:
private void LeftPreviousScoresButton_Click(object sender, RoutedEventArgs e)
{
if (m_previousScoresWindow.Visibility == Visibility.Visible)
{
m_previousScoresWindow.Hide();
WindowTitle = string.Empty;
PreviousScoresA.Clear();
PreviousScoresB.Clear();
}
else
{
WindowTitle = "Left Side";
// do not re-initialize the collection; clear and add new values
// PreviousScoresA = m_previousLeftWristErosionScoresReaderA;
// PreviousScoresB = m_previousLeftWristErosionScoresReaderB;
ReFillScores(PreviousScoresA, m_previousLeftWristErosionScoresReaderA);
ReFillScores(PreviousScoresB, m_previousLeftWristErosionScoresReaderB);
m_previousScoresWindow.Show();
}
}
private void ReFillScores (ObservableCollection<PreviousScoreData> collection, IEnumerable<PreviousScoreData> values)
{
collection.Clear();
foreach(PreviousScoreData d in values)
{
collection.Add(d);
}
}