2011-09-02 45 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