【问题标题】:Programatically bringing a Datagrid row into view in WPF, MVVM以编程方式在 WPF、MVVM 中显示 Datagrid 行
【发布时间】:2012-04-12 20:13:13
【问题描述】:

我想以编程方式将我的数据网格的一行显示在视图中。我有超过 100 行。当我创建一行时(我正在通过将一个项目添加到可观察集合中来执行此操作),我希望选择该新行并将其显示在视图中。我能够在我的代码中选择新行,但无法进行滚动。此外,我希望该行的第一个单元格处于编辑模式,以便用户可以输入文本。我正在关注应用程序的 MVVM 模式,并希望在我的视图中保持零代码。我怎样才能做到这一点?

任何帮助或建议将不胜感激......

更新:

这就是我在 XAML 中所做的

<telerik:RadGridView ItemsSource="{Binding AllPartClasses}" 
                     SelectedItem="{Binding SelectedPartClassViewModel, Mode=TwoWay}"         
                     SelectionMode="Single" IsSynchronizedWithCurrentItem="True">

在我的视图模型中我这样做了

void AddNewPartClassExecute()
    {
        PartClass newPartClass = new PartClass();
        PartClassViewModel tempPartClass = new PartClassViewModel(newPartClass);
        tempPartClass.IsInValid = true;
        AllPartClasses.Add(tempPartClass);
        SelectedPartClassViewModel = tempPartClass;
        Global.DbContext.PartClasses.AddObject(newPartClass);

        //OnPropertyChanged("AllPartClasses");
    }
public PartClassViewModel SelectedPartClassViewModel 
    { 
        get
        {  
            return _selectedPartClassViewModel;
        }
        set
        {
            _selectedPartClassViewModel = value;
            OnPropertyChanged("SelectedPartClassViewModel");
        }
    }

它对我不起作用。

【问题讨论】:

  • 被否决,因为标题中使用的“DataGrid”不是 RadGridView,这会破坏搜索结果。
  • 另外,这应该被否决,因为从未标记过正确答案,即@KornMuffin's。

标签: wpf mvvm datagrid


【解决方案1】:

对于常规 WPF DataGrid,您可以使用 ScrollIntoView。在您的视图中,将 SelectionChanged 事件连接到视图代码隐藏 cs 文件中的以下内容。

private void OnSelectionChanged( object sender, SelectionChangedEventArgs e )
{
    Selector selector = sender as Selector;
    DataGrid dataGrid = selector as DataGrid;
    if ( dataGrid != null && selector.SelectedItem != null && dataGrid.SelectedIndex >= 0 )
    {
        dataGrid.ScrollIntoView( selector.SelectedItem );
    }
}

【讨论】:

  • 或更简单的:if (sender is DataGrid dg) { if (dg.SelectedItem != null) dg.ScrollIntoView(dg.SelectedItem); }
【解决方案2】:

遵循 MVVM 模式时,您不应执行特定于 UI 的操作,例如从代码中滚动。

解决方案很简单 - 只需将 DataGrid.SelectedItem 绑定到 ViewModel 中的属性,当在项目集合中添加新项目时,只需更新绑定到 SelectedItem 的属性,这样它就会引用刚刚添加的项目和数据网格应该选择自动选择合适的行。

<DataGrid 
    ItemsSource="{Binding UnderyingItemsCollection}" 
    SelectedItem="{Binding RecentlyAddedItem, Mode=TwoWay}"
    IsSynchronizedWithCurrentItem="True">

【讨论】:

  • 非常感谢您的关注。我按照你的建议做了。但还没有运气。我在更新部分添加了我的代码。如果我遗漏了什么,请告诉我。我确实得到了选定的行,但是我该怎么做才能让数据网格滚动到底行...?
  • 我试过了,但它没有滚动到SelectedItem 行。我试图从 viewModel 更改 SelectedItem,但是 DataGrid 没有滚动到 SelectedItem 行。
  • 对我不起作用。这证明了不能总是严格使用 MVVM 模式。
  • 投了反对票,因为这个答案完全不相关。他已经能够从 VM 中进行选择,问题是如何将其纳入视野。
猜你喜欢
  • 2016-09-30
  • 2010-12-29
  • 2012-10-23
  • 1970-01-01
  • 2015-10-29
  • 1970-01-01
  • 2020-05-21
  • 2014-05-12
  • 1970-01-01
相关资源
最近更新 更多