2011-05-04 110 views
1

我想創建一個自定義控件類型,其行爲與ListBox完全相同,只不過它顯示的標題高於它。將標題添加到現有控件

我想我需要做的是繼承ListBox和使用如下代碼:

var originalTree = Template.VisualTree; 

var panel = new FrameworkElementFactory(typeof(StackPanel)); 

var heading = new FrameworkElementFactory(typeof(TextBlock)); 
heading.SetValue(TextBlock.TextProperty, "Heading"); 

panel.AppendChild(heading); 
panel.AppendChild(originalTree); 

Template.VisualTree = panel; 

除無論我試圖把它,它沒有工作,因爲Template.VisualTreenull。我究竟做錯了什麼?

+0

@downvoter,小心解釋爲什麼你低估了這個問題? – svick 2011-05-13 07:04:18

回答

1

據我知道模板可以以各種方式來定義,如果是VisualTreenull,已經「通過引用」中產生,在這種情況下,已被設定與Frameworktemplate.Template

編輯是意,所有成員都是內部或專用

,如果你要採取整根反正我會用一個用戶控件。


編輯:複製和編輯默認模板應罰款爲好,這裏是默認樣式:

<SolidColorBrush x:Key="ListBorder" Color="#828790"/> 
    <Style TargetType="{x:Type ListBox}"> 
     <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/> 
     <Setter Property="BorderBrush" Value="{StaticResource ListBorder}"/> 
     <Setter Property="BorderThickness" Value="1"/> 
     <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/> 
     <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/> 
     <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/> 
     <Setter Property="ScrollViewer.CanContentScroll" Value="true"/> 
     <Setter Property="ScrollViewer.PanningMode" Value="Both"/> 
     <Setter Property="Stylus.IsFlicksEnabled" Value="False"/> 
     <Setter Property="VerticalContentAlignment" Value="Center"/> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="{x:Type ListBox}"> 
        <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="1" SnapsToDevicePixels="true"> 
         <ScrollViewer Focusable="false" Padding="{TemplateBinding Padding}"> 
          <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> 
         </ScrollViewer> 
        </Border> 
        <ControlTemplate.Triggers> 
         <Trigger Property="IsEnabled" Value="false"> 
          <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/> 
         </Trigger> 
         <Trigger Property="IsGrouping" Value="true"> 
          <Setter Property="ScrollViewer.CanContentScroll" Value="false"/> 
         </Trigger> 
        </ControlTemplate.Triggers> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 

(你可以在頭綁定TextBox.TextListBox.Tag那你就不要需要繼承它)

默認模板和樣式是on MSDN

+0

我不想使用'UserControl',因爲我想使用'ListBox'的所有現有功能,包括它的模板。 – svick 2011-05-04 13:44:00

+0

您可以使用所有現有功能,只需傳播所有屬性,事件和方法。那麼,這些是相當多的,所以你也可以公開內部列表框,這意味着你的路徑會更長一些。 – 2011-05-04 13:45:40

+0

這就是爲什麼我認爲如果我只是繼承了'ListBox',它會更清潔。 – svick 2011-05-04 13:53:43