在Silverlight DataGrid中展开/折叠按钮

时间:2011-03-08 12:50:11

标签: silverlight datagrid

我在Silverlight DataGrid中使用RowDetailsTemplate来显示行详细信息。设置RowDetailsVisibilityMode =“VisibleWhenSelected”不能提供良好的用户体验(一次只能扩展一行,所有行都不能折叠)。在每一行上添加展开/折叠按钮以便可以独立展开/折叠行的最简单方法是什么?

1 个答案:

答案 0 :(得分:4)

我一直想写我的解决方案。 我将网格RowDetailsVisibilityMode设置为Collapsed并使用带有样式化ToggleButton的DataGridTemplateColumn来切换行可见性。

可以使用绑定或TriggerAction连接切换按钮以切换行可见性 绑定必须在代码隐藏中完成,因为您尝试将ToggleButton.IsChecked绑定到生成的元素并且在XAML中不存在(DataGridRow.DetailsVisibility) (这将在SL5中允许具有更强的RelativeSource绑定)

对于这两种解决方案,我在辅助类中都有这个扩展方法:

    /// <summary>
    /// Walk up the VisualTree, returning first parent object of the type supplied as type parameter
    /// </summary>
    public static T FindAncestor<T>(this DependencyObject obj) where T : DependencyObject
    {
        while (obj != null)
        {
            T o = obj as T;
            if (o != null)
                return o;

            obj = VisualTreeHelper.GetParent(obj);
        }
        return null;
    }

对于代码隐藏绑定方法:

    private void ToggleButton_Loaded(object sender, RoutedEventArgs e)
    {
        ToggleButton button = sender as ToggleButton;
        DataGridRow row = button.FindAncestor<DataGridRow>();  //Custom Extension
        row.SetBinding(DataGridRow.DetailsVisibilityProperty, new Binding() 
        {   
            Source = button, 
            Path = new PropertyPath("IsChecked"), 
            Converter = new VisibilityConverter(), 
            Mode = BindingMode.TwoWay 
        });
    }

对于TriggerAction方法:

public class ExpandRowAction : TriggerAction<ToggleButton>
{
    protected override void Invoke(object o)
    {
        var row = this.AssociatedObject.FindAncestor<DataGridRow>();
        if (row != null)
        {
            if (this.AssociatedObject.IsChecked == true)
                row.DetailsVisibility = Visibility.Visible;
            else
                row.DetailsVisibility = Visibility.Collapsed;
        }
    }
}

然后在XAML中:

<sdk:DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <ToggleButton Style="{StaticResource PlusMinusToggleButtonStyle}" >
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <behaviors:ExpandRowAction/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </ToggleButton>
    </DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
相关问题