40

WPFでボタンのデフォルトのテキストラッピングスタイルを変更するにはどうすればよいですか?

次の明らかな解決策:

<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="TextWrapping" Value="Wrap"></Setter>
</Style>

ここでは Textwrapping が設定可能なプロパティではないため、機能しません。

私が試してみると:

<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <TextBlock Text="{Binding}" Foreground="White" FontSize="20" FontFamily="Global User Interface" TextWrapping="Wrap"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

コンパイラから価値のない応答が返されます。

Error   5   After a 'SetterBaseCollection' is in use (sealed), it cannot be modified.   

ControlTemplate タグを削除すると、エラーが保持されます。

次の試行では、別のエラーが発生します。

    <Setter Property="TextBlock">
        <TextBlock Text="{Binding}" Foreground="White" FontSize="20" FontFamily="Global User Interface" TextWrapping="Wrap"/>
    </Setter>

Error   5   The type 'Setter' does not support direct content.  

ボタンごとにテキストの折り返しを個別に設定できることがわかりましたが、それはかなりばかげています。スタイルとしてはどうすればいいですか?魔法の言葉とは?

将来の参考のために、これらの魔法の言葉のリストはどこにありますか?セッターがどのプロパティを設定できるかを調べようとすると、MSDN エントリはほとんど役に立ちません。

4

6 に答える 6

46

ボタンに a を追加し、それを使用してボタンのプロパティTextBlockの代わりにボタンのテキストを表示することで、この問題を解決しました。の高さプロパティをContentに設定して、折り返すときにテキストの行数に合わせて高さが大きくなるようにしてください。TextBlockAuto

于 2010-12-17T01:08:31.423 に答える
32

あなたの2番目のバージョンは動作するはずです.TextBlock Textバインディングを変更する必要があるという警告があります.

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

これはボタン スタイルを完全に置き換えることに注意してください (つまり、必要に応じて独自のボタン クロムを作成する必要があります)。

2 番目の質問に関しては、すべての書き込み可能な依存関係プロパティは、Setter を使用して設定できます。スタイルを介して Button に TextWrapping を設定できなかった理由は、Button に TextWrapping 依存関係プロパティ (または実際には TextWrapping プロパティ) がないためです。"魔法の言葉" はありません。依存関係プロパティの名前だけです。

于 2009-04-15T23:45:47.073 に答える
5

C# コード ビハインドでの Eric の回答の例を次に示します。

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
};
于 2014-08-30T18:47:45.787 に答える