简体   繁体   中英

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 .

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM