2011-08-12 44 views
0

我有一個網格的附加屬性。它用於自動佈置網格內的內容控件。基本上,它是通過Children集合並將每個控件放入Grid控件的下一個空閒單元格中。它只完成一次(在Initialized事件處理程序中)。附加屬性在設計器視圖中重置

public static readonly DependencyProperty AutoLayoutProperty = 
     DependencyProperty.RegisterAttached(
      "AutoLayout", 
      typeof(bool), 
      typeof(GridEx), 
      new UIPropertyMetadata(false, OnAutoLayoutChanged)); 

    private static void OnAutoLayoutChanged(
     DependencyObject d, 
     DependencyPropertyChangedEventArgs e) 
    { 
     var grid = d as Grid; 
     if (!grid.IsInitialized) 
      grid.Initialized += new EventHandler(grid_Initialized); 
     else { UpdateLayout(grid); } 
    } 
    private static void UpdateLayout(Grid grid) 
    { 
     foreach(var child in grid.Children) 
     { 
      // Set Grid.Column and Grid.Row properties on the child 
     } 
    } 

此代碼的工作,並做我需要的一切,但有一個問題 - 當我編輯網格的內容在Expression Blend設計上的子控件的Grid.Column和Grid.Row性能得到復位。這只是煩人的。我能做些什麼來檢測Blend設計器的刷新,並將這些附加屬性重新應用於網格兒童?

回答

0

請嘗試使用Loaded事件。

編輯 - 增加了對設計師的解決方法

private static void OnAutoLayoutChanged(
    DependencyObject d, 
    DependencyPropertyChangedEventArgs e) 
{ 
    var grid = d as Grid;    
    grid.Loaded += (object sender, RoutedEventArgs e2) => 
    { 
     UpdateLayout(grid); 
    }; 

    // Workaround for Blend.. 
    if (DesignerProperties.GetIsInDesignMode(grid) == true) 
    { 
     grid.LayoutUpdated += (object sender, EventArgs e2) => 
     { 
      UpdateLayout(grid); 
     }; 
    } 
} 
+0

不幸的是沒有幫助。我一旦例如刪除網格內的控件所有其他的孩子在設計器中重置爲Grid.Row = 0和Grid.Column = 0。 – Jefim

+0

@Jefim:我明白你的意思了。我爲設計人員添加了一個解決方法。看看它是否適合你 –

+0

謝謝!這就像一個魅力! – Jefim

相關問題