Nar*_*esh 5 silverlight datagrid
我在Silverlight DataGrid中使用RowDetailsTemplate来显示行详细信息.设置RowDetailsVisibilityMode ="VisibleWhenSelected"不能提供良好的用户体验(一次只能扩展一行,所有行都不能折叠).在每行上添加展开/折叠按钮的最简单方法是什么,以便可以独立展开/折叠行?
我一直想在博客上写下我的解决方案。我将网格 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;
}
Run Code Online (Sandbox Code Playgroud)
对于代码隐藏绑定方法:
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
});
}
Run Code Online (Sandbox Code Playgroud)
对于 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在 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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5465 次 |
| 最近记录: |