开发者

Attached property being reset in designer view

I have an attached property for a Grid. It is used to automatically lay out the content controls inside the Grid. What is basically does is that it goes through the Children collection and puts every control in the next free cell of the Grid control. It is done once (in the Initialized event handler).

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

    private static void OnAutoLayoutChanged(
        DependencyObject d, 
        DependencyPropertyCh开发者_如何学JAVAangedEventArgs 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
        }
    }

This code works and does everything I need, yet there is one problem - when I edit the contents of the grid in Expression Blend designer those Grid.Column and Grid.Row properties on child controls get reset. It is just annoying. What can I do to detect the refresh of the Blend designer and reapply those attached properties to grid children?


Try with the Loaded event instead.

Edit - Added workaround for designer

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜