Search code examples
c#wpfxamlwinui-3

WinUI3: How to bind one control to the size of another control


I hope to get the height of a list, multiply it by 0.4, and set it to the Maxlength of a button.
For a reason, I don't want to use Grid, StackPanel, or other layout panel.
Here is what I have

<Window x:Class="App1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid>
        <ListBox x:Name="listBox" />
        <Button x:Name="button" Content="Click me!" />
    </Grid>

</Window>

Solution

  • Quoting from the docs:

    Although it has an ActualHeightProperty backing field, ActualHeight does not raise property change notifications and it should be thought of as a regular property and not a dependency property.

    You might be able to find some tricks to achieve this but the easiest way is to just use the SizeChanged event.

    public MainWindow()
    {
        InitializeComponent();
        this.listBox.SizeChanged += listBox_SizeChanged;
    }
    
    private void listBox_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        this.button.Height = this.listBox.ActualHeight * 0.4;
    }