2016-04-24 101 views
2

我有一个自动调整我的按钮的(文本)内容的问题。WPF ItemsControl弹出ButtonContent的FontSize

这是我的按钮的样式。没什么特别的,但注意TextWrapping属性!

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

我定义了一个ItemTemplate中基于我的按钮:

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

我显示的项目与ItemsControl中有3列一个清单:直到此时

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

,这没什么特别的。但现在,我希望所有按钮的FontSize最大限度地扩展,具有最大内容的项目允许(所有项目在最后应具有相同的FontSize)。我发现solution来计算所需的文本大小。所以我可以计算Button的最大FontSize。但是,因此我需要我的一个按钮的实际尺寸(都具有相同的尺寸)。

我真的不知道如何获得大小和解决我的问题。如果任何人有一个想法 - 或者完全不同的方法,那将是非常棒的。

回答

0

您可以使用按钮CommandParameter的ActualWidth的获得宽度是这样的:

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

那么你的命令应该是这样的:

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

     private void ExecuteCommand(object obj) 
     { 
      double width = (double)obj; 
     } 
+1

我需要的宽度之前,我使用的任何命令。 – Fruchtzwerg

+0

我编辑了我的答案,以便获取UserControl的加载事件的值。 – Johannes