2013-01-08 65 views
0

之前更新我有由幾個結合ItemsControl的和strings的,並且基於被按下的按鈕UserControl,將顯示不同的數據。這裏是Button的單擊事件的一個示例:ItemsControl的對結合不顯示

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(); 
    } 
} 

有幾種其分配WindowTitlePreviousScoresA,並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}" /> 

然而,打開窗戶時,舊的數據顯示用於第二前將其與當前的數據進行更新。我甚至試過呼籲WindowHide()時加入這些電話,但它似乎並沒有幫助:

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

有什麼辦法,以確保Show()不叫,直到綁定數據已更新後?謝謝。

回答

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); 
    } 
} 
+0

我試過了,但問題仍然存在。爲什麼一個'ObservableCollections <>'永遠不會被重新初始化?應該使用'List <>'來代替嗎? – Saggio