使用時要覆蓋一個控制整個模板,使用DataTemplate
當你想告訴WPF如何繪製一個數據對象(通常是DataContext
),並使用ContentTemplate
當你想告訴WPF如何ControlTemplate
繪製一個對象的Content
屬性。
創建一個全新的ControlTemplate
是相當複雜的。爲了演示,請this MSDN example爲一個Button
一個例子ControlTemplate
。
在你的情況,我會建議爲你的按鈕Style
與制定者共同屬性,如Height
,Width
,Font
等,如果你想畫你的按鈕在自定義的方式Content
屬性,而不完全覆蓋按鈕模板,包含ContentTemplate
樣式設置器,以告訴WPF如何繪製Button.Content
屬性。
<Button Style="{StaticResource CalculatorButton}" Content="1" />
和
<Style x:Key="CalculatorButton" TargetType="{x:Type Button}">
<Setter Property="Height" Value="50"/>
<Setter Property="Width" Value="50"/>
<Setter Property="FontSize" Value="14" />
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="{Binding }" FontFamily="Wingdings 3" FontWeight="Bold" FontSize="18" Foreground="Navy" />
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
的ControlTemplate
定義按鈕看上去如何,所述ContentTemplate
定義Button.Content
長相如何,並且用於ContentTemplate
的DataTemplate
是定義如何的「1」中的數據對象將畫。
這看起來非常好。一些問題:(1)'{Binding}'應該是空的嗎?這是否告訴它查看在XAML中添加每個按鈕時指定的'Content'屬性? (2)你的最後一個'Setter'指定了'Value ='並且在它下面有另一個'',這是錯誤的嗎? –
對於這兩個問題都是肯定的:)'{Binding}'應該是空的,所以它只會顯示當前數據上下文是什麼,在本例中就是'Button.Content',在我的例子中我有一個錯誤,已經設置了兩次「Value」屬性。我會編輯我的答案,刪除該,謝謝。 – Rachel
謝謝!還有最後一個問題......你怎麼知道'Button.Content'是它會引用的數據上下文?我不熟悉它是這種事情的「搜索模式」。 –