Ex Quetto
Ex Quetto

Reputation: 1

Get column width if it is set to "2*" to Binding in xaml WPF?

I have StackPanel in the third column of Grid "MainGrid". It's(third column) width set to "2*".

I want to hide StackPanel using margin and then use slide animation to show it.

So i need to set Margin of StackPanel to Column[2] Width, but how can i get it? I'm trying this:

Margin="{Binding ElementName=MainGrid, Path=ColumnDefinitions[2].ActualWidth, Converter={StaticResource marginConverter}}

So, i add breakpoint to converter in code-behind and it always get 0.

I've tried to use MainGrid.ActualWidth insted of Column[2] ActualWidth and it send to converter at first zero, then it's actual width.

Upvotes: 0

Views: 199

Answers (1)

Alex.Wei
Alex.Wei

Reputation: 1883

Unfortunately, ColumnDefinition.ActualWidth is not a dependency property, that means it will not report the update. A quick solution is write a new class inherit from ColumnDefinition and notify ActualWidth is changed everytime the parent Grid had updated its layout. And instead of ColumnDefinition, use this class in xaml.

public class MyColumnDefinition : ColumnDefinition, INotifyPropertyChanged
{
    public MyColumnDefinition() : base() { }

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        ((Grid)Parent).LayoutUpdated += MyColumnDefinition_LayoutUpdated;
    }

    private void MyColumnDefinition_LayoutUpdated(object sender, EventArgs e)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ActualWidth"));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Upvotes: 0

Related Questions