1

ButtonやHeaderedContentControlなど、テキストに下線が引かれているコンテンツコントロールのテンプレートを作成しようとしています。

Content="This text is underlined"指定されたときにテキストに下線を付けたいだけです。

コンテンツが別のUIElementである場合は、通常どおり機能し続ける必要があります。

これと同じ質問をするほとんどの投稿は、コンテンツとして文字列に対してのみ機能するようにテンプレートを変更することに満足しています。Scott Guには、ボタンのスタイリングに関する優れた記事がありますが、この問題には対処していません。

次のサンプルは、文字列ではなくContent型のインスタンスとして実際に渡す場合に機能します。TextBlock確かに、ビジュアルツリーにはTextBlockがあるので、スタイルを設定する必要があります。おそらくこれはSivlerlightの制限です。

この例では、大きな赤いテキストとして両方を表示したい場合に、黒いテキストと大きな赤いテキストを示しています。

    <navigation:Page.Resources>
    <Style TargetType="TextBlock" x:Key="style123">
        <Setter Property="Foreground"  Value="Red"/>
        <Setter Property="FontSize" Value="72"/>
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="TextDecorations" Value="Underline"/>
    </Style>
</navigation:Page.Resources>

<StackPanel>        

    <!-- This doesn't work and shows black text -->
    <ContentPresenter Content="Small black text">
        <ContentPresenter.Resources>
            <Style TargetType="TextBlock" BasedOn="{StaticResource style123}"/>
        </ContentPresenter.Resources>
    </ContentPresenter>

    <!-- This works and shows red text -->
    <ContentPresenter>
        <ContentPresenter.Content>
            <TextBlock Text="This is big red text"/>
        </ContentPresenter.Content>

        <ContentPresenter.Resources>
            <Style TargetType="TextBlock" BasedOn="{StaticResource style123}"/>
        </ContentPresenter.Resources>
    </ContentPresenter>

</StackPanel>
4

2 に答える 2

1

newContentが文字列の場合、プロパティを下線付きにリセットするために、使用している実際のContentControl(つまりButton)をサブクラス化し、オーバーライドすることができます。newContentが文字列でない場合、通常の方法で実行されます。OnContentChangedContentTextBlock

public class UnderlineButton : Button
{
    protected override void OnContentChanged(object oldContent, object newContent)
    {
        if (newContent is string)
        {
            TextBlock textBlock = new TextBlock();
            textBlock.Text = newContent as string;
            textBlock.TextDecorations = TextDecorations.Underline;
            this.Content = textBlock;
        }

        base.OnContentChanged(oldContent, newContent);
    }
}

これを達成するためだけにサブクラス化するのはちょっと面倒ですが、面倒なスタイルテンプレートとサブクラス化を回避しContentPresenterます。

于 2010-08-12T15:36:33.247 に答える
0

DataTemplateを使用してstringコンテンツをカスタムレンダリングして、この例を試してください(背景を赤に設定しただけです)。

<ContentControl Content="{Binding YourData}" >
  <ContentControl.Resources>
    <DataTemplate DataType="{x:Type s:String}">
      <TextBlock Text="{Binding}" Background="Red" />
    </DataTemplate>
  </ContentControl.Resources>
</ContentControl>

編集:メモとして、ContentControlより良い再利用性が必要な場合は、毎回インラインで適用するのではなく、これをスタイルに引き出すことができます...

于 2010-08-12T15:48:39.790 に答える