从XAML获取行索引

3

我有一个DataGrid,其中包含DataGridTemplateColumns。在模板列中,我使用了一个DataTrigger,它能正常工作。它从DataGrid的父级中检索Item Count。

<DataGridTemplateColumn>                                                         
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
             ...
             <!-- this works fine! -->
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor,
                AncestorType={x:Type DataGrid}}, Path=Items.Count}" Value="1">
                    ...
             </DataTrigger>
          </DataTemplate>

是否有可能获取模板所在的当前行索引? 我认为可以绑定到当前的DataGridRow。但是"GetIndex()"这样的绑定路径不会被支持,例如:

<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
    AncestorType={x:Type DataGridRow}}, Path=GetIndex()}" Value="0"> <!-- error: GetIndex() -->

有没有一种替代方法可以在xaml中绑定到DataGridRow.GetIndex()

1个回答

4

您只能绑定到对象的属性,而不能绑定到方法。如果您想要绑定到方法,则需要使用IValueConverter

public class MyConverter : DependencyObject, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
                             System.Globalization.CultureInfo culture)
    {
        return (value as DataGridRow).GetIndex();
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                               System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

并将其绑定如下 -
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
                        AncestorType={x:Type DataGridRow}},
                        Converter={StaticResource MyConverter}}"
            Value="0">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接