1

I have a problem autosizing the (Text)Content of my buttons.

This is the style of my Buttons. Nothing special but notice the TextWrapping property!

<Style TargetType="{x:Type Button}">
  <Setter Property="Template">
  <Setter.Value>
    <ControlTemplate TargetType="Button">
      <TextBlock Text="{TemplateBinding Content}" TextWrapping="Wrap"/>
    </Setter.Value>
  </Setter>
</Style>

I defined a ItemTemplate based on my Buttons:

<DataTemplate x:Key="MyItemTemplate">
  <Button Content="{Binding Content}" Command="{Binding Command}" FontWeight="Bold" FontSize="{Binding FontSize}"/>
</DataTemplate>

I am showing a list of items in with a ItemsControl with 3 columns:

<ItemsControl ItemsSource="{Binding MyItems}" ItemTemplate="{StaticResource MyItemTemplate}">
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <UniformGrid Columns="3"/>
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
</ItemsControl>

Until this point, this is nothing special. But now, I want the FontSize of all my Buttons stretched to maximum possible, the item with the largest content allows (all items should have the same FontSize in the end).

I found a solution to calculate the needed size of a text. So I could calculate the maximum FontSize of a Button. But therefore I need the actual size of one of my Buttons (all have the same size).

I have not really an idea how to get the size and solve my problem. Would be great if anybody has an idea - or a totally different approach.

Community
  • 1
  • 1
Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49

1 Answers1

0

You can use ActualWidth of your Button as CommandParameter to get the width like this :

<UserControl ....
.................>
<i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded">
            <i:InvokeCommandAction Command="{Binding Command}" CommandParameter="{Binding ActualWidth,ElementName=button}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>

    <DataTemplate x:Key="MyItemTemplate">
                    <Button Content="{Binding Content}" x:Name="button"
                    Command="{Binding Command}"
                    FontWeight="Bold" FontSize="{Binding FontSize}"/>
                </DataTemplate>

your Command should then be like this :

        public ICommand Command => new DelegateCommand<object>(ExecuteCommand);

        private void ExecuteCommand(object obj)
        {
            double width = (double)obj;
        }
  • I edited my answer so you get the value on the loaded event of UserControl. –  Apr 25 '16 at 05:11