代码之家  ›  专栏  ›  技术社区  ›  Simon_Weaver

当内容是字符串时,是否为在Silverlight中为ContentPresenter创建的隐式文本块加下划线?

  •  1
  • Simon_Weaver  · 技术社区  · 14 年前

    我正在尝试为内容控件(如button或headeredContentControl等)创建模板,其中的文本带有下划线。

    我只想在文字下加下划线 Content="This text is underlined" 指定。

    如果内容是另一个uielement,它必须继续正常工作。

    大多数提出相同问题的文章都对修改模板以仅对字符串作为内容工作感到满意。古司各特有一篇关于 styling buttons 但不能解决这个问题。

    如果你真的通过的话,下面的例子会起作用。 Content 作为类型的实例 TextBlock 但不是一根绳子。当然,可视化树有一个文本块,因此它应该为其设置样式。也许这是一个六倍的限制。

    当我希望黑色文本和大红色文本同时显示为大红色文本时,此示例显示黑色文本和大红色文本。

        <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>
    
    2 回复  |  直到 11 年前
        1
  •  1
  •   Spontifixus    11 年前

    你可以把任何实际的 ContentControl (即 Button )您正在使用和重写 OnContentChanged 为了重置 Content 属性设置为带下划线 TextBlock 如果新内容是字符串。在新内容不是字符串的情况下,它将以通常的方式执行。

    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 .

        2
  •  0
  •   Dan Puzey    14 年前

    尝试此示例,使用数据模板自定义呈现 string 内容(我刚刚将背景设置为红色):

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

    编辑:就像一张纸条,你可以把它放到 ContentControl 如果您需要更好的可重用性,请选择样式而不是每次都内联应用它…