2011-09-02 91 views
0

这是一个两部分问题,可能有类似的答案。风格标签主图像和文字

我想在资源字典中创建标签的样式,该标签首先包含图像,然后是文本。该文本作为TextBlock具有它自己的风格(在那里没有问题)。以下是我有

标签样式:

<Style x:Key="LabelStyle" TargetType="Label"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="Label"> 
       <TextBlock Style="{StaticResource TextBlockStyle}"> 
       </TextBlock> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

TextBlockStyle:

<Style x:Key="TextBlockStyle" TargetType="{x:Type TextBlock}"> 
    <Setter Property="Margin" Value="25 0 0 2.5"/> 
    <Setter Property="Width" Value="Auto"/> 
    <Setter Property="HorizontalAlignment" Value="Left"/> 
    <Style.Triggers> 
     <Trigger Property="IsMouseOver" Value="True"> 
      <Setter Property="TextDecorations" Value="Underline"/> 
      <Setter Property="Foreground" Value="Blue"/> 
      <Setter Property="Cursor" Value="Hand"/> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

现在我的问题是,当我添加一个新的标签,我的控制(例如:窗口)并指定文本(例如:创建),没有文字显示。类似于:

<Label Style="{StaticResource LabelStyle}">Create</Label> 

文本创建不显示,但是如果我放在我显示的LabelStyle-> TextBlock->文本中,但是它不好,因为我想为不同的标签更改它。有没有办法将我的标签文本绑定到我的(内部样式)TextBlock.Text ???

我的其他问题是相同的,但对于图像和Image.Source。

感谢:-)

编辑:

这是我现在有H.B.回答实施

<Style x:Key="LabelStyle" TargetType="Label"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="Label"> 
       <Grid> 
        <StackPanel Orientation="Horizontal"> 
         <Image Source="/Resources/Create.png" /> 
         <TextBlock Style="{StaticResource TextBlockStyle}" Text="{TemplateBinding Content}"/> 
        </StackPanel> 
       </Grid> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

请注意,这是在资源字典中。对于TextBlock,它的效果很好。但对于图像来说,这是一个不同的故事。我希望与'Text ='{TemplateBinding Content}'一样,但是对于Image.Source并且在我添加标签时将其设置为我的控件的路径。可能由于它是多个内容,我必须编写更多的代码, d很喜欢,但我会解决最简单,最干净的答案。

HB再次感谢和超链接,这仍然在开发中,它不会在任何超链接,只是一些自定义菜单按钮与一些动画所以它不是用户很无聊:P

+0

如果你有内容这样你可以创建一个['用户控件'](http://msdn.microsoft.com/en-us/library/system.windows.controls.usercontrol.aspx),那么你可以为'TextBlock.Text'和'Image.Source'创建一个属性。您也可以滥用Image.Source-TemplateBinding的['Tag'](http://msdn.microsoft.com/zh-cn/library/system.windows.frameworkelement.tag.aspx)。另一个替代方案是使用动态资源,如[这里]所示(http://stackoverflow.com/questions/4638741/template-binding-in-control-template/4638822#4638822)。 –

+0

谢谢,我想我会去UserControl。它更简单,快捷,可定制和更少的代码行。非常感谢 – David

回答

1

Label.Template不再将LabelContent属性(你设置为"Create")到任何内部部分为了解决这个问题,你可以例如结合TextBlock.Text等。这个:

<ControlTemplate TargetType="Label"> 
    <TextBlock Style="{StaticResource TextBlockStyle}" 
       Text="{TemplateBinding Content}"/> 
</ControlTemplate> 

(我只注意到你让标签看起来像一个超链接,你一定要明白,there already is a class的,对吧?)

+0

谢谢,这正是我需要:)))至于图像?是相同的(或类似的)? – David

+0

你在做什么形象,你改变它的模板?请提供尽可能多的信息。 –

+0

@ H.B如果标签内容不是纯文本,那么绑定会执行什么操作....? – loxxy