从xaml获取RowIndex

时间:2012-11-22 15:20:43

标签: wpf datagrid

我有一个带DataGridTemplateColumns的DataGrid。在TemplateColumn中,我使用DataTrigger工作正常。它从DataGrid父级检索项目计数。

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

是否有可能检索放置模板的当前RowIndex? 我认为可以绑定到当前的DataGridRow。不支持“GetIndex()”的绑定路径,例如:

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

是否可以从xaml绑定到DataGridRow.GetIndex()

1 个答案:

答案 0 :(得分:3)

您只能绑定到Properties而不能绑定对象的方法。如果要绑定到方法 -

,则需要使用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">