wpf - 如何在 WPF 中创建环绕按钮

标签 wpf xaml layout button

要求:

  • 必须支持 MinWidth 属性
  • 只能显示一行或两行文本。无法换行至 3 个或更多。
  • 应使按钮尽可能小,同时尊重 MinWidth
  • 文本只能在空格上换行
  • 无法指定宽度。按钮应保持水平方向增长。

这是我希望按钮的样子(请忽略样式,包装是重要的部分)

enter image description here

我正在寻找有关如何使文本动态换行的想法。

最佳答案

我尝试通过编辑 Button 的默认模板来实现这一点,主要是添加一个包装 TextBlock 而不是默认的 ContentPresenter 并计算其转换器中的宽度。不过,这种方法需要转换器中的大量数据,可能有更简单(而且更好:)的方法来做到这一点,但无论如何它似乎都有效。由于默认模板中存在 ButtonChrome,因此需要引用 PresentationFramework.Aero

像这样使用它

<Button Style="{StaticResource WrappingButton}"
        MinWidth="100"
        Content="This button has some long text">
</Button>

enter image description here
StackPanel 中包含 3 个 WrappingButtons 的屏幕截图示例

WrappingButton 样式

<Style x:Key="WrappingButton" TargetType="{x:Type Button}"
       xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero">
    <Setter Property="HorizontalAlignment" Value="Left"/>
    <Setter Property="Width" Value="Auto"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <ControlTemplate.Resources>
                    <local:WrappingButtonWidthConverter x:Key="WrappingButtonWidthConverter"/>
                </ControlTemplate.Resources>
                <Microsoft_Windows_Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" RenderDefaulted="{TemplateBinding IsDefaulted}" SnapsToDevicePixels="true">
                    <TextBlock VerticalAlignment="Center"
                               FontSize="{TemplateBinding FontSize}"
                               FontFamily="{TemplateBinding FontFamily}"
                               FontStyle="{TemplateBinding FontStyle}"
                               FontWeight="{TemplateBinding FontWeight}"
                               FontStretch="{TemplateBinding FontStretch}"
                               LineStackingStrategy="BlockLineHeight"
                               TextWrapping="Wrap"
                               TextTrimming="WordEllipsis"
                               Text="{Binding RelativeSource={RelativeSource TemplatedParent},
                                              Path=Content}">
                        <TextBlock.Width>
                            <MultiBinding Converter="{StaticResource WrappingButtonWidthConverter}">
                                <Binding RelativeSource="{RelativeSource Self}" Path="Text"/>
                                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="FontFamily"/>
                                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="FontStyle"/>
                                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="FontWeight"/>
                                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="FontStretch"/>
                                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="FontSize"/>
                                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="MinWidth"/>
                            </MultiBinding>
                        </TextBlock.Width>
                    </TextBlock>
                </Microsoft_Windows_Themes:ButtonChrome>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsKeyboardFocused" Value="true">
                        <Setter Property="RenderDefaulted" TargetName="Chrome" Value="true"/>
                    </Trigger>
                    <Trigger Property="ToggleButton.IsChecked" Value="true">
                        <Setter Property="RenderPressed" TargetName="Chrome" Value="true"/>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Foreground" Value="#ADADAD"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

WrappingButtonWidthConverter

public class WrappingButtonWidthConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string text = values[0].ToString();
        FontFamily fontFamily = values[1] as FontFamily;
        FontStyle fontStyle = (FontStyle)values[2];
        FontWeight fontWeight = (FontWeight)values[3];
        FontStretch fontStretch = (FontStretch)values[4];
        double fontSize = (double)values[5];
        double minWidth = (double)values[6];

        string[] words = text.Split(new char[] {' '});
        double widthSum = 0.0;
        List<double> wordWidths = GetWordWidths(words, fontFamily, fontStyle, fontWeight, fontStretch, fontSize, out widthSum);

        double width = 0.0;
        for (int i = 0; width < (widthSum / 2.0) && i < wordWidths.Count; i++)
        {
            width += wordWidths[i];
        }

        return minWidth > 0.0 ? Math.Max(minWidth, width) : width;
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    private List<double> GetWordWidths(string[] words,
                                       FontFamily fontFamily,
                                       FontStyle fontStyle,
                                       FontWeight fontWeight,
                                       FontStretch fontStretch,
                                       double fontSize,
                                       out double widthSum)
    {
        List<double> wordWidths = new List<double>();
        widthSum = 0.0;
        foreach (string word in words)
        {
            Typeface myTypeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);
            FormattedText ft = new FormattedText(word + " ",
                                                 CultureInfo.CurrentCulture,
                                                 FlowDirection.LeftToRight,
                                                 myTypeface,
                                                 fontSize,
                                                 Brushes.Black);
            wordWidths.Add(ft.WidthIncludingTrailingWhitespace);
            widthSum += ft.WidthIncludingTrailingWhitespace;
        }
        return wordWidths;
    }
}

关于wpf - 如何在 WPF 中创建环绕按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6865477/

相关文章:

wpf - Silverlight按钮样式如何在按下按钮时防止其处于聚焦状态?

c# - 通过 USB 类列出 USB 设备

magento - 从观察者覆盖整个magento布局

wpf - 如何确定内容的宽度或容器的大小以适应内容

c# - Listbox ItemTemplate Selector 不选择模板

wpf - 如何在 csproj 中构建着色器效果 (.fx)

c# - 获取图表上 LinearAxis 的自动间隔值 (System.Windows.Controls.DataVisualization.Charting)

wpf - 为什么在这种情况下无法解析 StaticResource?

java - 新手 Q : layout_below not placing my button below my textView

android - 如何为 S4 设计布局