重用TreeView在WPF中展开[+]并折叠[ - ]按钮

M. *_*ley 1 wpf treeview button reusability togglebutton

有没有办法重用WPF中节点旁边出现的简单展开[+]和折叠[-]按钮TreeView?我想在我的应用程序的其他地方有一个类似的图形来扩展和折叠一些控件.

Car*_*rlo 10

它实际上是一个ToggleButton,我检查了SimpleStyles项目上的TreeView模板,这是我发现的:

    <ControlTemplate TargetType="ToggleButton">
      <Grid
        Width="15"
        Height="13"
        Background="Transparent">
        <Path x:Name="ExpandPath"
          HorizontalAlignment="Left" 
          VerticalAlignment="Center" 
          Margin="1,1,1,1"
          Fill="{StaticResource GlyphBrush}"
          Data="M 4 0 L 8 4 L 4 8 Z"/>
      </Grid>
      <ControlTemplate.Triggers>
        <Trigger Property="IsChecked"
             Value="True">
          <Setter Property="Data"
              TargetName="ExpandPath"
              Value="M 0 4 L 8 4 L 4 8 Z"/>
        </Trigger>
      </ControlTemplate.Triggers>
    </ControlTemplate>
Run Code Online (Sandbox Code Playgroud)

所以这就是你需要做的才能让它发挥作用:

<Window x:Class="StackOverflowTests.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" x:Name="window1" Height="300" Width="300"
 Loaded="window1_Loaded"
 xmlns:local="clr-namespace:StackOverflowTests">
 <Window.Resources>
  <SolidColorBrush x:Key="GlyphBrush" Color="#444" />
  <ControlTemplate x:Key="toggleButtonTemplate" TargetType="ToggleButton">
   <Grid
            Width="15"
            Height="13"
            Background="Transparent">
    <Path x:Name="ExpandPath"
              HorizontalAlignment="Left" 
              VerticalAlignment="Center" 
              Margin="1,1,1,1"
              Fill="{StaticResource GlyphBrush}"
              Data="M 4 0 L 8 4 L 4 8 Z"/>
   </Grid>
   <ControlTemplate.Triggers>
    <Trigger Property="IsChecked"
                 Value="True">
     <Setter Property="Data"
                  TargetName="ExpandPath"
                  Value="M 0 4 L 8 4 L 4 8 Z"/>
    </Trigger>
   </ControlTemplate.Triggers>
  </ControlTemplate>
  <Style x:Key="toggleButtonStyle" TargetType="ToggleButton">
   <Setter Property="Template" Value="{StaticResource toggleButtonTemplate}" />
  </Style>
 </Window.Resources>
 <StackPanel>
  <ToggleButton x:Name="toggleButton" Height="20" Width="20" Style="{StaticResource toggleButtonStyle}" />
 </StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)
  • 首先,您获取模板(toggleButtonTemplate)并将其放入您的资源中
  • 然后你创建一个样式(toggleButtonStyle)来设置控件的模板(toggleButtonTemplate)
  • 最后你告诉你的ToggleButton它的样式是toggleButtonStyle

如果您只是将粘贴复制到它应该直接工作.

这是一个简单的过程,但如果您不习惯使用模板,它会让您头疼,如果您有任何疑问,请告诉我.

要学习一些迷你语言的路径:

几何迷你语言