2015-02-08 103 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) 
     { 

     } 
    } 

现在,它的工作。 谢谢