2011-03-08 161 views
5

我在Silverlight DataGrid中使用RowDetailsTemplate來顯示行詳細信息。設置RowDetailsVisibilityMode =「VisibleWhenSelected」沒有提供良好的用戶體驗(一次只能擴展一行,所有行不能摺疊)。在每一行上添加展開/摺疊按鈕的最簡單方法是什麼,以便行可以獨立展開/摺疊?在Silverlight DataGrid中展開/摺疊按鈕

回答

4

我一直在意味着博客我的解決方案。 我將網格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> 
+0

感謝。這就像一個魅力!我遇到的麻煩是PlusMinusToggleButtonStyle。我創建了切換兩張圖像的樣式,但這不起作用。我將爲此發佈一個單獨的問題。 – Naresh 2011-03-09 03:37:26

+1

無恥自我推銷:在我的網站上發佈博客解決方案[mikeherman.net](http://mikeherman.net/blog/workarounds-for-weaker-relativesource-binding-in-silverlight-4)。 – foson 2011-03-28 00:32:48