我在Silverlight DataGrid中使用RowDetailsTemplate来显示行的详细信息。设置RowDetailsVisibilityMode="VisibleWhenSelected“不能提供良好的用户体验(一次只能展开一行,不能折叠所有行)。在每一行上添加展开/折叠按钮,以便可以单独展开/折叠各行,最简单的方法是什么?
发布于 2011-03-08 23:33:38
我一直想把我对此的解决方案写到博客上。我将网格RowDetailsVisibilityMode设置为折叠,并使用其中带有样式ToggleButton的DataGridTemplateColumn来切换行可见性。
切换按钮可以连接起来,使用绑定或通过TriggerAction切换行可见性。
绑定必须在代码隐藏中完成,因为您正在尝试将ToggleButton.IsChecked绑定到一个生成的元素,该元素在XAML (DataGridRow.DetailsVisibility)中不存在(这在具有更强RelativeSource绑定的SL5中是允许的)
对于这两种解决方案,我在一个helper类中都有这个扩展方法:
/// <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>https://stackoverflow.com/questions/5232683
复制相似问题