WPF MVVM - запускать стрелку направления сортировки данных программно - PullRequest
0 голосов
/ 14 мая 2018

По умолчанию, когда загружается моя DataGrid, мои данные будут отсортированы по ProductName asc. Однако в заголовке ProductName gridview не будет отображаться значок стрелки вверх. Это в любом случае для меня, чтобы вызвать значок программно?

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:

<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 ]

0 голосов
/ 01 февраля 2019

Если вы хотите синхронизировать эффективную сортировку с визуальным стилем столбца, это должно помочь:

( (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;
                }
            }
        }
    }
}
0 голосов
/ 14 мая 2018

Добавьте следующее к DataGridTextColumn:

SortDirection="Ascending" 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...