2015-02-08 126 views
1

我在兩個不同的地方使用mvvm綁定datagrid時遇到了一個問題。我的數據網格(XAML)的頭是:使用MVVM的Datagrid綁定WPF

<DataGrid Grid.Row="0" Grid.Column="0" AlternationCount="2" Background="White" RowHeight="28" HorizontalGridLinesBrush="Lavender" VerticalGridLinesBrush="Lavender" 
      VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" IsSynchronizedWithCurrentItem="True" 
      ScrollViewer.CanContentScroll="True" Name="MainGrid" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Visible" 
      HorizontalAlignment="Stretch" VerticalAlignment="Stretch" AutoGenerateColumns="False" CanUserAddRows="False" 
      CanUserDeleteRows="False" CanUserResizeRows="True" ItemsSource="{Binding Path=Configurations, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"> 

這clealy說

ItemsSource="{Binding Path=Configurations, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" 

在我的視圖模型:

public ObservableCollection<ViewerConfiguration> Configurations 
{ 
    get { return m_tasks; } 
    set { m_tasks = value; OnPropertyChanged("Configurations"); } 
} 

,在列表中正確顯示在視圖中的數據,但問題在於插入和刪除(即使更新成功)。 我有在配置對象

private void Refresh() 
{ 
    List<ViewerConfiguration> newlyAddedFiles = GetConfigurations(); 
    foreach (ViewerConfiguration config in newlyAddedFiles) 
    { 
     Configurations.Add(config); 
    } 
} 

插入一個項目,並移除像功能:

Configurations.Remove(configuration); 

的問題是真正與插入和刪除。在調試時沒有異常,它也成功從集合中刪除,但UI沒有收到通知。任何猜測爲什麼是這種行爲?

此外: 我有一個事件觸發剛下的DataGrid:

<i:Interaction.Triggers> 
    <i:EventTrigger EventName="SelectionChanged"> 
     <i:InvokeCommandAction Command="{Binding RenderPdf}" CommandParameter="{Binding SelectedItem, ElementName=MainGrid}"></i:InvokeCommandAction> 
    </i:EventTrigger> 
</i:Interaction.Triggers> 

和我打電話從視圖模型的構造刷新功能只是爲了看看是否可行與否。

+0

是你的刪除,並添加生成一個事件?我懷疑它...... – 2015-02-08 16:37:00

+0

@TMcKeown它確實如果它是一個ObservableCollection。 – 2015-02-08 16:37:59

+0

發佈完整的代碼。你的問題不清楚。您目前顯示的代碼似乎沒有任何問題。 – 2015-02-08 16:38:21

回答

0

最後我解決了我遇到的問題。基本上有兩個問題。在配置的getter中,我在排序和過濾前一個之後返回了一個新的可觀察集合。 第二個主要問題:

'This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread' 

這是我最好的猜測,我改變了我的刷新功能:

private void Refresh() 
    { 
     try 
     { 
      List<ViewerConfiguration> newlyAddedFiles = GetConfigurations(); 
      //should not update on other thread than on main thread 
      App.Current.Dispatcher.BeginInvoke((ThreadStart)delegate() 
      { 
       foreach (ViewerConfiguration config in newlyAddedFiles) 
       { 
        Configurations.Add(config); 
       } 
      }); 
     } 
     catch (Exception ex) 
     { 

     } 
    } 

現在,它的工作。 謝謝