可以使用 Converter 有条件地定义 SortMemberPath 吗?

Possible to define SortMemberPath conditionally with Converter?

我有一个 DataGrid,其中包含一个列,该列由 StackPanel 中的 2 个不同的可排序项目共享。

这些项目都是 NameA/NameB 的,我想要的是 SortMemberPath 根据名为 'sortByNameB'.

的布尔状态在这两者之间进行更改

我在想的是使用一个带有静态资源的转换器来检查 sortByNameB 的状态,然后 returns 一些东西到 SortMemberPath.. 但我不确定应该返回什么?我尝试将字符串返回为 "NameA"/"NameB" 但这只会破坏排序。

相关XAML:

<DataGridTemplateColumn Header="Names" SortMemberPath="{Binding Converter={StaticResource NameSort}}">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical" VerticalAlignment="Center">
                <TextBlock Padding="1" HorizontalAlignment="Center">
                    <Hyperlink NavigateUri="{Binding Path=NameA}" RequestNavigate="Name_RequestNavigate">
                        <TextBlock Text="{Binding Path=NameA}" Foreground="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource FGName}}"/>
                    </Hyperlink>
                </TextBlock>
                <TextBlock Padding="1" HorizontalAlignment="Center">
                    <Hyperlink NavigateUri="{Binding Path=NameA}" RequestNavigate="Name_RequestNavigate">
                        <TextBlock Text="{Binding Path=NameB}" Foreground="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource FGName}}"/>
                    </Hyperlink>
                </TextBlock>
            </StackPanel>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

转换器:

public class NameSort : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        return (ToolView.sortByNameB) ? "NameB" : "NameA";
    }
}

如果硬编码 "NameA",排序是否有效?如果是这样,那么转换器将工作,因为它返回相同的东西,其他地方出了问题。

你的 SortMemberPath 应该绑定到 Path=sortByNameB, Converter=... 不过。现在它只是绑定到对象本身,所以当 sortByNameB 更改时你不会调用转换器,我认为这就是你所说的 "breaks the sorting"?

我想出了一个方法。

我有一个控制 sortByNameB 状态的复选框,为了这个例子,DataGrid 被命名为 "dataGrid",在 Checked/Unchecked 事件中添加:

string toSortBy = (sortByNameB) ? "NameB" : "NameA";
dataGrid.ColumnFromDisplayIndex(1).SortMemberPath = toSortBy;

其中“1”是名称列的列索引。

不确定这是否是一种真正优雅的方式,希望通过 xaml 中的绑定来实现,但至少很简单。