MVVM子对话框datagrid没有填充

时间:2014-03-21 17:07:12

标签: c# wpf mvvm datagrid

我正在用MVVM编写一个wpf应用程序。我的任务是在显示模型对话框中填充搜索结果,该对话框具有数据网格。我能够将数据检索到父视图模型中,但它没有在子对话框中填充。请帮我解决我做错的地方。代码编写如下:

对话框视图:

 <DataGrid Name="grdSearchResult" Grid.Column="0" Grid.Row="0" GridLinesVisibility="All" 
              ItemsSource="{Binding Path=SearchResult, ElementName=SearchResultWindow}" 
              AutoGenerateColumns="False" Width="470" Height="250" Margin="0,5,0,0">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" IsReadOnly="True" Width="40" Binding="{Binding Path=Id}"/>
            <DataGridTextColumn Header="Object Name" IsReadOnly="True" Width="175" Binding="{Binding Path=ObjName}"/>
            <DataGridTextColumn Header="Object Type" IsReadOnly="True" Width="175" Binding="{Binding Path=ObjTyp}"/>
            <DataGridCheckBoxColumn Header="Locate" IsReadOnly="True" Width="50">                    
            </DataGridCheckBoxColumn>
        </DataGrid.Columns>
    </DataGrid>

视图模型:

public void performQuickSearch(){

LabelTextOfCustomCtrl = this.SearchPattern;
      string s = this.SearchPattern;

        if (!String.IsNullOrEmpty(SearchPattern)) {

        private ObservableCollection<QuickSearchResult> _searchResult = new ObservableCollection<QuickSearchResult>();

                         var result = ERUSDataProvider.Instance.QuickSearch(SearchPattern);

                    if (result != null) {
                       result.ToList().ForEach(val => _searchResult.Add(new QuickSearchResult {
                    Id = val.Id,
                    ObjName = val.ObjName,
                    ObjTyp = val.ObjTyp
                }));
            }

            SearchResultDialog dialogue = new SearchResultDialog();
            dialogue.DataContext = this;
            dialogue.Owner = App.Current.MainWindow;
            dialogue.ShowDialog();
        }

}

与resultType:

enter code here

public class QuickSearchResult : ViewModelBase {
    public int? Id { get; set; }
    public string ObjName { get; set; }
    public string ObjTyp { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您正在撰写MVVM,但做错了。您为什么要从ViewModel分享DialogWindow

此外,对ElementName的{​​{1}}进行绑定也无济于事,因为DialogModal dialog相比具有不同的Visual Tree

我建议您创建自己的MainWindow并将其DialogViewModel设置为该对象。确保实现DataContext并在INotifyPropertyChanged属性上引发事件。