1

我有一个 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 设置为一个列表:

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

DataGridTemplateColumn 中的 ComboBox 的 ItemsSource 绑定到我的窗口中的一个属性:

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”的属性。很明显,当我尝试对该列进行排序时说属性“DisplayText”在对象“InsertableRecord”中不存在时出现绑定错误。

我将如何根据组合框的当前文本(或“房间”对象的 DisplayText 属性,两者都可以)对列进行排序?

4

1 回答 1

1

好的,我暂时创建了一个小技巧:我在 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 并提取其当前文本值......但这并没有似乎不是一个选择...

任何其他提议都将不胜感激,因为这是我将在整个应用程序中重用的模式,并且我希望使其尽可能干净以避免重写重复代码......

于 2013-08-12T16:03:19.223 回答