0

我有一个UserControl由几个 boundItemsControl和 组成的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}" />

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

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

有什么方法可以确保Show()在绑定数据更新之前不会调用它?谢谢。

4

1 回答 1

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);
  }
}
于 2013-01-08T18:16:31.750 回答