WPF button textwrap style

前提是你 提交于 2019-11-29 09:04:21

Your second version should work, and does for me, with the caveat that you need to change the TextBlock Text binding:

<!-- in Window.Resources -->
<Style x:Key="fie" TargetType="Button">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Button}">
        <TextBlock Text="{TemplateBinding Content}" FontSize="20" TextWrapping="Wrap"/>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

<!-- then -->
<Button Style="{StaticResource fie}">verylongcaptiongoeshereandwraps/Button>

Note this completely replaces the button style (i.e. you will need to create your own button chrome if you want it).

Regarding your second question, all writeable dependency properties can be set using a Setter. The reason you were unable to set TextWrapping on a Button via a style is that Button does not have a TextWrapping dependency property (or indeed any TextWrapping property). There are no "magic words," just the names of dependency properties.

To expand Eric's answer with an example:-

<Button Name="btnName" Width="50" Height="40">
   <TextBlock Text="Some long text" TextWrapping="Wrap" TextAlignment="Center"/>
</Button>
Eric

I solved this problem by adding a TextBlock to the button, and using it to display the button text instead of the button's Content property. Be sure to set the TextBlock's height property to Auto, so that it grows in height to accommodate the number of lines of text as it wraps.

<Style TargetType="Button">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock Text="{TemplateBinding Content}" TextWrapping="Wrap" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

Here's an example of Eric's answer in C# code-behind:

var MyButton = new Button();

MyButton.Content = new TextBlock() {
    FontSize        = 25,
    Text            = "Hello world, I'm a pretty long button!",
    TextAlignment   = TextAlignment.Center,
    TextWrapping    = TextWrapping.Wrap
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!