2016-09-08 119 views
0

我創建的自ContentControl繼承的控制和XAML寫道風格:自定義內容控制不顯示內容模板

<Style TargetType="{x:Type controls:ButtonPopup}"> 
    <Setter Property="ContentTemplate"> 
     <Setter.Value> 
      <DataTemplate> 
       <Border> 
        <StackPanel> 
         <ContentPresenter Content="{TemplateBinding ContentControl.Content}" /> 
        </StackPanel> 
       </Border> 
      </DataTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

當我想用我的控制像下面我看不到任何內容

<controls:ButtonPopup Width="100" 
         Height="100"> 
       <Button Content="button"></Button> 
</controls:ButtonPopup> 

一切正常,如果我用我的風格在標準內容控制

<ContentControl Style="{StaticResource PopupContentStyle2}"> 
       <Button Content="button"></Button> 
</ContentControl> 

<Style x:Key="PopupContentStyle2" TargetType="{x:Type ContentControl}"> 
      <Setter Property="ContentTemplate"> 
       <Setter.Value> 
        <DataTemplate> 
         <Border Width="100" Height="100"> 

          <StackPanel Width="100" Height="100"> 
           <TextBlock Text="SDADASDSADA" /> 
           <ContentPresenter Width="100" Height="100" Content="{TemplateBinding ContentControl.Content}" /> 
          </StackPanel> 

         </Border> 
        </DataTemplate> 
       </Setter.Value> 
      </Setter> 
     </Style> 

瓦在我的控制問題?

+0

將代碼複製/粘貼到一個新項目以及'public class ButtonPopup:ContentControl {'''可以正常工作,所以我懷疑這個問題實際上是在'ButtonPopup'實現中。那個自定義控件是什麼樣子的? – Rachel

+0

@Rachel,謝謝你,你的回答給我提供了找到問題的線索。我在這樣的靜態構造函數中重寫DefaultStyleKey的默認值: DefaultStyleKeyProperty.OverrideMetadata(typeof(ButtonPopup),new FrameworkPropertyMetadata(typeof(ButtonPopup))); 控制工作沒有這個。爲什麼我不能那樣做? – Quisy

回答

0

你有一個內容模板,再次引用內容,你不應該這樣做。您應該改爲設置Control.Template

該模板甚至沒有應用,因爲您已經提供了一個UIElement,它不需要模板化。 ContentTemplates應該用於模板數據。

0

而不是設置ContentTemplate您可能想要設置派生ContentControl的Template。 TemplateBinding在ControlTemplate中工作。

<Style TargetType="controls:ButtonPopup"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="controls:ButtonPopup"> 
       <Border> 
        <StackPanel> 
         <ContentPresenter Content="{TemplateBinding Content}" /> 
        </StackPanel> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

這也不清楚爲什麼在一個邊框內只有一個孩子的StackPanel。