在Silverlight DataGrid中展开/折叠按钮
问题描述:
我在Silverlight DataGrid中使用RowDetailsTemplate来显示行详细信息。设置RowDetailsVisibilityMode =“VisibleWhenSelected”没有提供良好的用户体验(一次只能扩展一行,所有行不能折叠)。在每一行上添加展开/折叠按钮的最简单方法是什么,以便行可以独立展开/折叠?在Silverlight DataGrid中展开/折叠按钮
答
我一直在意味着博客我的解决方案。 我将网格RowDetailsVisibilityMode设置为Collapsed,并使用DataGridTemplateColumn和其中的样式化ToggleButton切换行可见性。
可以使用绑定或通过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
});
}
对于特里格erAction方法:
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>
感谢。这就像一个魅力!我遇到的麻烦是PlusMinusToggleButtonStyle。我创建了切换两张图像的样式,但这不起作用。我将为此发布一个单独的问题。 – Naresh 2011-03-09 03:37:26
无耻自我推销:在我的网站上发布博客解决方案[mikeherman.net](http://mikeherman.net/blog/workarounds-for-weaker-relativesource-binding-in-silverlight-4)。 – foson 2011-03-28 00:32:48