Evenly-sized buttons according to content of largest button

前端 未结 3 1491
[愿得一人]
[愿得一人] 2020-12-13 18:54

Imagine I have two WPF buttons on a window, with content as follows:



I

3条回答
  •  感动是毒
    2020-12-13 19:00

    I like using a wrap panel for this type of scenario. When it's loaded I get the max width from all children using linq. (assuming children are all buttons)

    xaml

    
    

    cs

    WP_ButtonSelections.Children.Add(new Button() { Content = "Hello" });
    WP_ButtonSelections.Children.Add(new Button() { Content = "Hello World" });
    
    
    private void WP_ButtonSelections_Loaded(object sender, RoutedEventArgs e)
    {
       double maxWidth = WP_ButtonSelections.Children.OfType().Max(elm => elm.ActualWidth);
       WP_ButtonSelections.Children.OfType().ToList().ForEach(elm => elm.Width = maxWidth);
    }
    

    I needed a programmatic solution. This requires the loaded event because programmatically added buttons wont have an ActualWidth defined upon calling WP_ButtonSelections.Children.Add(). This solution should work with xaml defined buttons, or a mixture of both xaml and programmatic.

提交回复
热议问题