2016-04-24 71 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