[英]Bound ItemsControl not updating before displaying
我有一個UserControl
,它由一些綁定的ItemsControl
和strings
,並且根據所按下的按鈕,將顯示不同的數據。 這是Button
的click事件之一的示例:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.