【问题标题】:WPF MVVM - Trigger datagrid sort direction's arrow programmaticallyWPF MVVM - 以编程方式触发数据网格排序方向的箭头
【发布时间】:2018-10-24 04:01:57
【问题描述】:

默认情况下,加载我的 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;
    }
}

【问题讨论】:

标签: c# wpf mvvm datagrid


【解决方案1】:

将以下内容添加到DataGridTextColumn

SortDirection="Ascending" 

【讨论】:

    【解决方案2】:

    如果您想将有效排序与列上的视觉样式同步,这应该会有所帮助:

    ( (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;
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-02
      • 1970-01-01
      • 2013-05-13
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 2012-12-01
      • 1970-01-01
      相关资源
      最近更新 更多