Search code examples
c#wpfdata-bindingdatagrid

I want my binded DataGrid to NOT sort the ItemsSource too


I have a DataGrid which I bound to a ObservableCollection via the ItemsSource-Property. This DataGrid is IsReadOnly="True" and AutoGenerateColumns="False". (Columns were added in the XAML)

So far everything works, but: When i sort a by a column, the ItemsSource gets sorted, too. I want the user to be able to sort the columns without the actual ItemsSource being sorted too.

Is that possible and if so how do i manage that?

Edit: Problem should be reproducable with this. When you click on Number-header, the ComboBox items have the same new order as the DataGrid.

XAML of MainWindow:

<DockPanel LastChildFill="True">
    <ComboBox DockPanel.Dock="Bottom" Name="cbItems" IsEditable="True"/>
    <DataGrid Name="dataGrid" AutoGenerateColumns="False" IsReadOnly="True">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Name}" Header="Name"/>
            <DataGridTextColumn Binding="{Binding SomeNumber}" Header="SomeNumber"/>
        </DataGrid.Columns>
    </DataGrid>
</DockPanel>

Code:

public partial class MainWindow : Window
{
    ObservableCollection<Item> ItemList;

    public MainWindow()
    {
        InitializeComponent();

        ItemList = new ObservableCollection<Item>();

        Random rnd = new Random();
        for(int i = 0; i < 15; i++)
            ItemList.Add(new Item("blabla" + rnd.Next(10, 100), rnd.Next(10000, 100000)));

        dataGrid.ItemsSource = ItemList;
        cbItems.ItemsSource = ItemList;
    }
}

public class Item
{
    private string name;
    private int number;

    public Item(string name, int number)
    {
        this.name = name;
        this.number = number;
    }

    public string Name { get { return name; } set { name = value; } }
    public int SomeNumber { get { return number; } set { number = value; } }

    public override string ToString()
    {
        return name;
    }
}

Solution

  • You should be able to overcome the fact both controls will reference the same collection view by setting the ItemsSource properties to two independant views:

    dataGrid.ItemsSource = new ListCollectionView(ItemList);
    cbItems.ItemsSource = new ListCollectionView(ItemList);