使用ComboBox对DataGridTemplateColumn进行排序

时间:2013-08-09 18:14:45

标签: c# wpf sorting datagrid

我有一个DataGrid,只有一列(为了这个例子)。此列是DataGridTemplateColumn:

<DataGrid x:Name="grdMainGrid">
    <DataGridTemplateColumn Header="Room" CanUserSort="True" SortMemberPath="DisplayText" >
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <ComboBox ItemsSource="{Binding Path=AllRooms, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" Height="20" SelectedValuePath="Code" SelectedValue="{Binding Path=RoomCode, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="DisplayText" />
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid>

DataGrid的ItemsSource设置为List:

public class InsertableRecord
{
    public int RoomCode { get; set; }
}

DataGridTemplateColumn中的ComboBox的ItemsSource绑定到我的Window中的属性:

public List<Room> AllRooms
{
    get;
    private set;
}

以下是“房间”类的定义:

public partial class Room
{
    public string ID { get; set; }

    public string Description { get; set; }

    public string DisplayText
    {
        get
        {
            return this.ID + " (" + this.Description + ")";
        }
    }
}

请注意,我将SortMemberPath设置为DisplayText,它是“Room”的属性,而不是“InsertableRecord”。很明显,当我尝试对此列进行排序时,我在对象“InsertableRecord”中不存在属性“DisplayText”时出现绑定错误。

我如何根据ComboBox的当前Text(或“Room”对象的DisplayText属性)对列进行排序,这两种方法都有效??

1 个答案:

答案 0 :(得分:0)

好的,暂时,我创造了一个小黑客: 我在InsertableRecord中创建了一个名为SelectedDisplayText的新属性。

public class InsertableRecord
{
    public int RoomCode { get; set; }
    public string SelectedDisplayText { get; set; }
}

然后我将DataGrid列定义更改为:

<DataGrid x:Name="grdMainGrid">
    <DataGridTemplateColumn Header="Room" CanUserSort="True" **SortMemberPath="SelectedDisplayText"** >
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <ComboBox ItemsSource="{Binding Path=AllRooms, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" Height="20" SelectedValuePath="Code" SelectedValue="{Binding Path=RoomCode, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="DisplayText" **Text="{Binding Path=SelectedDisplayText, Mode=OneWayToSource}"** />
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid>

现在有了这个,每次我改变组合框的选择时,组合框的新“选定文本”会填充在InsertableRecord对象的“SelectedDisplayText”中,然后数据网格可以根据它进行排序。那个价值。

现在这个有效,但它仍然感觉像是一个黑客。我想除了可以有一种方法来构建一个自定义排序,通过正在处理的行的数据上下文,我可以获得该行的相关ComboBox并提取其当前文本值...但这不是似乎是一个选择...

任何其他命题都会受到赞赏,因为这是我将在整个应用程序中重复使用的模式,我希望尽可能保持干净以避免重写重复代码......

相关问题