Как растянуть текст в квадратную кнопку? - PullRequest
8 голосов
/ 18 февраля 2012

В моем приложении у меня есть сетка из квадратных кнопок. Текстовое содержимое для каждой кнопки устанавливается во время выполнения. В большинстве случаев текст имеет длину всего один символ, но иногда он длиннее. Мне нужно сделать так, чтобы весь текст был всегда видимым, то есть растянуть его (изменить размер шрифта), чтобы он поместился внутри границы кнопки. Как мне это сделать?

Я пытался использовать Viewbox, но это не помогло.

Упрощенная версия моего XAML:

<Viewbox Stretch="Uniform">
    <Button Content="Text" 
            Width="{Binding ActualHeight, RelativeSource={RelativeSource Self}}"/>
</Viewbox>

Есть идеи о том, как мне добиться того, что мне нужно (например, квадратные кнопки + текст, который всегда умещается)?

1 Ответ

7 голосов
/ 18 февраля 2012

Ваше первоначальное предложение было почти правильным, попробуйте это:

    <Button>
        <Viewbox Stretch="Fill">
            <TextBlock Text="Test"/>
        </Viewbox>
    </Button>

И чтобы применить это к нескольким кнопкам:

    <Style x:Key="StretchedButtonContent" TargetType="{x:Type Button}">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Viewbox Stretch="Fill">
                        <ContentPresenter Content="{TemplateBinding Content}"/>
                    </Viewbox>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Button Style="{StaticResource StretchedButtonContent}" Content="Test" />

Моей первой мыслью было использование RenderTransform и конвертера. Это дает тот же результат, но более сложный:

    <Converters:ScaleConverter x:Key="ScaleConverter" />

    <Button>
        <TextBlock Text="Test" RenderTransformOrigin="0.5,0.5">
            <TextBlock.RenderTransform>
                <ScaleTransform>
                  <ScaleTransform.ScaleX>
                    <MultiBinding Converter="{StaticResource ScaleConverter}">
                        <Binding RelativeSource="{RelativeSource AncestorType={x:Type Button}}" Path="ActualWidth" />
                        <Binding RelativeSource="{RelativeSource AncestorType={x:Type TextBlock}}" Path="ActualWidth" />
                    </MultiBinding>
                  </ScaleTransform.ScaleX>
                  <ScaleTransform.ScaleY>
                    <MultiBinding Converter="{StaticResource ScaleConverter}">
                        <Binding RelativeSource="{RelativeSource AncestorType={x:Type Button}}" Path="ActualHeight" />
                        <Binding RelativeSource="{RelativeSource AncestorType={x:Type TextBlock}}" Path="ActualHeight" />
                    </MultiBinding>
                  </ScaleTransform.ScaleY>
                </ScaleTransform>
            </TextBlock.RenderTransform>
        </TextBlock>
    </Button

и конвертер

public class ScaleConverter : IMultiValueConverter
{
    #region Implementation of IMultiValueConverter

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return ((double) values[0])/((double) values[1]);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...