绑定ItemsControl在显示之前不更新

时间:2013-01-08 15:42:40

标签: c# wpf data-binding

我有UserControl由一些绑定的ItemsControlstrings组成,并且根据按下的按钮,会显示不同的数据。以下是其中一个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();
    }
}

这些点击事件监听器中有几个会为WindowTitlePreviousScoresAPreviousScoresB分配相关数据。 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}" />

但是,打开窗口时,旧数据会在使用当前数据更新之前显示一秒钟。我甚至尝试在Hide()上调用Window时添加这些来电,但似乎没有帮助:

WindowTitle = String.Empty;
PreviousScoresA = new ObservableCollection<PreviousScoreData>();
PreviousScoresB = new ObservableCollection<PreviousScoreData>();

有没有办法确保在绑定数据更新之后才调用Show()?感谢。

1 个答案:

答案 0 :(得分:0)

由于看起来您使用的是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);
  }
}