代码之家  ›  专栏  ›  技术社区  ›  Nerdynosaur

WPF MVVM-以编程方式触发datagrid排序方向的箭头

  •  0
  • Nerdynosaur  · 技术社区  · 6 年前

    默认情况下,当加载我的DataGrid时,我的数据将按ProductName asc排序。但是,gridview的ProductName标头不会显示向上箭头图标。我是否可以通过编程方式触发图标?

    XAML:

    <DataGrid x:Name="GridProduct" 
              ItemsSource="{Binding Path=ProductResult}" 
              Style="{StaticResource defaultDataGridStyle}" 
              CellStyle="{StaticResource defaultCellStyle}"
              ColumnHeaderStyle="{StaticResource defaultCellHeaderStyle}"> 
      <DataGrid.Columns>
           <DataGridTextColumn Header="Product Name" Binding="{Binding ProductName}" />
           <DataGridTextColumn Header="Product Price" Binding="{Binding ProducPrice}"/> 
      </DataGrid.Columns>
    </DataGrid>
    

    样式:

    <Style x:Key="defaultCellHeaderStyle" TargetType="DataGridColumnHeader" BasedOn="{StaticResource MetroDataGridColumnHeader}">
        <Setter Property="FontSize" Value="16"></Setter>
        <Setter Property="Command" Value="{Binding Path=DataContext.SortCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
        <Setter Property="CommandParameter" Value="{Binding Path=Content, RelativeSource={RelativeSource Self}}"></Setter>
    </Style>
    
    <Style x:Key="defaultCellStyle" TargetType="DataGridCell" BasedOn="{StaticResource MetroDataGridCell}">
        <Setter Property="FontSize" Value="16"></Setter>
        <Setter Property="HorizontalContentAlignment" Value="Center"></Setter>
        <Setter Property="HorizontalAlignment" Value="Stretch"></Setter>
    </Style>
    

    MVVM:

    public List<Product> ProductResult
    {
        get
        {
            _productResult = _productResult.OrderBy(x => x.Name).ToList();
            return _productResult;
        }
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   E Mett    6 年前

    将以下内容添加到 DataGridTextColumn :

    SortDirection="Ascending" 
    
        2
  •  1
  •   OK cowboy    5 年前

    如果要将有效排序与列上的视觉样式同步,这应有助于:

    ( (INotifyCollectionChanged)Items.SortDescriptions ).CollectionChanged += new NotifyCollectionChangedEventHandler( OnItemsSortDescriptionsChanged );
    
    
    private void OnItemsSortDescriptionsChanged( object sender, NotifyCollectionChangedEventArgs e )
    {
        //Synchronize effective sorting in the grid and Visual style on columns
        if ( Items != null )
        {
            foreach ( DataGridColumn column in Columns )
            {
                column.SortDirection = null;
    
                foreach ( SortDescription sd in Items.SortDescriptions )
                {
                    if ( column.SortMemberPath == sd.PropertyName )
                    {
                        column.SortDirection = sd.Direction;
                        break;
                    }
                }
            }
        }
    }