用于WPF DataGrid的ScrollIntoView(MVVM)

时间:2013-08-02 14:28:00

标签: c# wpf mvvm datagrid scroll

我正在使用MVVM模式,我在XAML中为DataGrid的SelectedItem创建了一个绑定。我以编程方式设置SelectedItem,但是当我这样做时,DataGrid不会滚动到选择。有没有办法在不完全打破MVVM模式的情况下实现这一目标?

我找到了以下解决方案但是当我尝试实现Behavior类时出现错误,即使我已经安装了Blend SDK:http://www.codeproject.com/Tips/125583/ScrollIntoView-for-a-DataGrid-when-using-MVVM

4 个答案:

答案 0 :(得分:31)

这应该有效。我们的想法是,您将附加到DataGrid附加的附加属性。在您附加它的xaml中,您将它绑定到ViewModel上的属性。每当您想以编程方式为SelectedItem分配值时,还要为此属性设置一个值,附加属性绑定到该属性。

我已将附加的属性类型设置为SelectedItem类型的任何类型,但老实说,只要将其设置为与以前不同的类型,类型是什么并不重要。此附加属性仅用作以MVVM友好方式在视图控件(在本例中为DataGrid)执行某些代码的方法。

那就是说,这是附属物的代码:

namespace MyAttachedProperties
{
    public class SelectingItemAttachedProperty
    {
        public static readonly DependencyProperty SelectingItemProperty = DependencyProperty.RegisterAttached(
            "SelectingItem",
            typeof(MySelectionType),
            typeof(SelectingItemAttachedProperty),
            new PropertyMetadata(default(MySelectionType), OnSelectingItemChanged));

        public static MySelectionType GetSelectingItem(DependencyObject target)
        {
            return (MySelectionType)target.GetValue(SelectingItemProperty);
        }

        public static void SetSelectingItem(DependencyObject target, MySelectionType value)
        {
            target.SetValue(SelectingItemProperty, value);
        }

        static void OnSelectingItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var grid = sender as DataGrid;
            if (grid == null || grid.SelectedItem == null)
                return;

            // Works with .Net 4.5
            grid.Dispatcher.InvokeAsync(() => 
            {
                grid.UpdateLayout();
                grid.ScrollIntoView(grid.SelectedItem, null);
            });

            // Works with .Net 4.0
            grid.Dispatcher.BeginInvoke((Action)(() =>
            {
                grid.UpdateLayout();
                grid.ScrollIntoView(grid.SelectedItem, null);
            }));
        }
    }
}

这是xaml片段:

<Window ...
        xmlns:attachedProperties="clr-namespace:MyAttachedProperties">
    ...
        <DataGrid 
            attachedProperties:SelectingItemAttachedProperty.SelectingItem="{Binding MyViewModel.SelectingItem}">
            ...
        </DataGrid>
    </Grid>

答案 1 :(得分:16)

我是MVVM的新手。我理解MVVM的想法,并尝试正确实现一切。 我上面遇到了类似的问题,最后我在XAML中输了1行,后面跟着1行代码。其余代码在VM中。 我在XAML中做了以下

<ListBox DockPanel.Dock="Top"
    Name="Selection1List" 
    ItemsSource="{Binding SelectedList1ItemsSource}" 
    SelectedItem="{Binding SelectedList1Item}"
    SelectedIndex="{Binding SelectedList1SelectedIndex}"
    SelectionChanged="Selection1List_SelectionChanged">

这在后面的代码中:

private void Selection1List_SelectionChanged(object sender, SelectionChangedEventArgs e) {
    Selection1List.ScrollIntoView(Selection1List.SelectedItem);
}

这很好。

我知道有些人甚至不想在窗口后面的代码中使用一行代码。但我认为这一行只是为了观点。它与数据或数据逻辑无关。所以我认为这不违反MVVM原则 - 而且更容易实现。

欢迎任何评论。

答案 2 :(得分:0)

@Edgar的解决方案工作正常,但是在我的应用程序中,我还必须检查SelectionChangedEventArgs的OriginalSource。

private void OperatorQualificationsTable_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if ((OperatorQualificationsTable.SelectedItem != null) && (e.OriginalSource?.Equals(OperatorQualificationsTable) ?? false))
    {
        OperatorQualificationsTable.ScrollIntoView(OperatorQualificationsTable.SelectedItem);
    }
}

我的数据网格包含以下ComboBoxColumn

<dgx:EnhancedDataGridComboBoxColumn 
    DisplayMemberPath="DescriptionNL"
    Header="{x:Static nl:Strings.Label_Qualification}"
    ItemsSource="{Binding Path=QualificationKeysView, Source={StaticResource ViewModel}}"
    SelectedValueBinding="{Binding ActivityQualification.QualificationKey}"
    SelectedValuePath="QualificationKey"/>

每次我向上或向下滚动时,组合框都会调用更改选择的事件,并且不再可能将所选项目移出视图。

答案 3 :(得分:0)

这是我使ScrollIntoView工作的解决方案。我在LayoutUpdated()事件中执行操作

public void ManipulateData()
{
    // Add a new record or what else is needed;
    myItemsSourceCollection.Add(...); 

    // Not needed when the ItemsSource is a ObervableCollectin 
    // with correct Binding (ItemsSource="{ Binding myItemsSourceElement }")
    myDataGrid.Items.Refresh();

    // Goto last Item or where ever
    myDataGrid.SelectedIndex = this.myDataGrid.Items.Count - 1;
}

// The LayoutUpdated event for the DataGrid
private void myDataGrid_LayoutUpdated(object sender, EventArgs e)
{
    if (myDataGrid.SelectedItem == null)
        return;
    //<----------

    // may become improved to check first if the `ScrollIntoView()` is really needed

    // To prevent hanging here the ItemsSource must be 
    // a) an ObervableCollection with a correct working binding or
    // b) myDataGrid.Items.Refresh(); must be called after changing
    // the data
    myDataGrid.ScrollIntoView(myDataGrid.SelectedItem, null);
}