当网格本身被排序时,如何让DataGrid对其进行排序以支持ObservableCollection?

时间:2011-06-21 06:49:07

标签: wpf binding wpfdatagrid

我有一个绑定到对象列表的网格,SelectedIndex绑定到一个属性,我希望这个SelectedIndex能正常工作,因为索引会在排序时发生变化,但是模型中的集合没有排序,因此索引与模型无关。

视图中的标记:

<DataGrid Name="gridCustomers"
          ItemsSource="{Binding Customers}"
          SelectedIndex="{Binding SelectedIndex}"
          CanUserSortColumns="True"
          SelectionUnit="FullRow">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Customer" Binding="{Binding ID}" />
        <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
    </DataGrid.Columns>
</DataGrid>

模型中的代码

public ObservableCollection<Customer> Customers {
    get;
    private set;
}

private int selectedIndex;
public int SelectedIndex {
    get { return selectedIndex; }
    set {
        if (selectedIndex != value) {
            selectedIndex = value;
            OnNotifyPropertyChanged("SelectedIndex");
            OnNotifyPropertyChanged("SelectedCustomer");
        }
    }
}

public Customer SelectedCustomer {
    get { return CustomersView[selectedIndex]; }
}

我正在使用这种方法,因为我有“下一个/上一个”按钮和一个标签绑定到“y of y customers”。 SelectedCustomer是子控件的便利属性,在这种情况下显示不正确的对象。

1 个答案:

答案 0 :(得分:1)

我设法通过使用SelectedIndexSelectedItem绑定属性来解决这个问题,而不是浏览列表本身。

查看:

<DataGrid Name="gridCustomers"
            ItemsSource="{Binding Path=Customers}"
            SelectedIndex="{Binding SelectedIndex}"
            SelectedItem="{Binding SelectedCustomer}"

型号:

public ObservableCollection<Customer> Customers {
    get;
    private set;
}

private int selectedIndex;
public int SelectedIndex {
    get { return selectedIndex; }
    set {
        if (selectedIndex != value) {
            selectedIndex = value;
            OnNotifyPropertyChanged("SelectedIndex");
            OnNotifyPropertyChanged("NavText");
        }
    }
}

private Customer selectedCustomer;
public Customer SelectedCustomer {
    get { return selectedCustomer; }
    set {
        if (!Object.Equals(selectedCustomer, value)) {
            selectedCustomer = value;
            OnNotifyPropertyChanged("SelectedCustomer");
        }
    }
}

public string NavText {
    get {
        if (Customers.Count == 0)
            return "No Customers";
        if (SelectedIndex == -1)
            return String.Format("{0} customers", customers.Count);
        return String.Format("{0} of {1}", SelectedIndex + 1, Customers.Count);
    }
}

public void First() {
    if (Customers.Count == 0)
        return;
    SelectedIndex = 0;
}

public void Last() {
    if (Customers.Count == 0)
        return;
    SelectedIndex = Customers.Count - 1;
}

public void Next() {
    if (Customers.Count == 0 || SelectedIndex == Customers.Count - 1)
        return;
    SelectedIndex++;
}

public void Previous() {
    if (Customers.Count == 0 || SelectedIndex <= 0)
        return;
    SelectedIndex--;
}