TreeViewItem Кнопка привязки команд - PullRequest
0 голосов
/ 28 октября 2010

Добрый день,

Первый вопрос здесь и просто изучение WPF, поэтому, пожалуйста, будьте осторожны ...

Я пытаюсь собрать TreeView, элементы которого запускают команды. Я уверен, что есть много способов сделать это, но мой подход состоял в том, чтобы создать Стиль для TreeViewItem с ControlTemplate, который включает RadioButton для его функциональности Command.

. . .
<ToggleButton x:Name="Expander"
  Style="{StaticResource ExpandCollapseToggleStyle}" Grid.Column="0" Grid.Row="0" 
  IsChecked="{Binding Path=IsExpanded, RelativeSource={RelativeSource TemplatedParent}}"
  ClickMode="Press"/>
  <RadioButton Style="{StaticResource TreeElementStyle}"
    Grid.Row="0" Grid.Column="1" Command="{TemplateBinding ???}">
    <ContentPresenter x:Name="PART_Header" ContentSource="Header"/>
  </RadioButton>
  <ItemsPresenter x:Name="ItemsHost" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2"/>
</Grid>
. . .

Несмотря на это, у меня дерево выглядит визуально хорошо, но я не могу понять, как связать мою Команду со встроенной кнопкой RadioButton, и теряюсь в трясине путаницы шаблонов.

. . .
<TreeView>
  <TreeViewItem Header="Enterprise">
    <TreeViewItem Header="General Settings"
      Command="{Binding Path=GeneralSettingsCommand}"/>
. . .

Я бы предоставил больше кода, но я полагаю, что в этот момент ответы будут более похожи на: "Чувак, ты не в курсе. Сначала читай про бла" или "Кнопка совершенно не нужна", или "вы должны использовать ItemTemplate вместо" или ... "или" просто сдаваться уже ";)

1 Ответ

0 голосов
/ 29 октября 2010

Спасибо, Мелеак; хорошая информация.

Однако я нашел очень простое решение - в любом случае для моих целей.

Весь трюк состоит в том, чтобы предоставить Button как TreeViewItem.Header, а не включать его в ControlTemplate TreeViewItem.

Если я предоставлю Button в качестве TreeViewItem.Header, я могу легко установить для него Команду и соответствующим образом оформить ее.

Вот пример:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Page.Resources>
    <Style TargetType="{x:Type RadioButton}">
      <Setter Property="GroupName" Value="TreeGroup"/>
      <Setter Property="Focusable" Value="False"/>
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type RadioButton}">
            <Grid >
              <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
              </Grid.ColumnDefinitions>
              <!-- beginnings of a folder icon -->
              <Border Background="Black" VerticalAlignment="Center" Width="12" Height="10" CornerRadius="2">
                <Border Background="DarkGoldenrod" Margin="1"/>
              </Border>
              <Border Grid.Column="1" Margin="4,0,0,0" Padding="1,2,4,2" Name="Selection" Background="Transparent">
                <ContentPresenter />
              </Border>
            </Grid>
            <ControlTemplate.Triggers>
              <Trigger Property="IsChecked" Value="True">
                <Setter TargetName="Selection" Property="Background" Value="DarkBlue"/>
                <Setter Property="Foreground" Value="White"/>
              </Trigger>
            </ControlTemplate.Triggers>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </Page.Resources>
  <Grid>  
     <TreeView Width="220" Focusable="False">
      <TreeViewItem IsExpanded="True">
        <TreeViewItem.Header>
          <RadioButton Content="Enterprise"/>
        </TreeViewItem.Header>
        <TreeViewItem>
          <TreeViewItem.Header>
            <RadioButton Content="Settings" Command="{Binding SettingsCommand}"/>
          </TreeViewItem.Header>
        </TreeViewItem>
        <TreeViewItem>
          <TreeViewItem.Header>
            <RadioButton Content="Statistics" Command="{Binding StatisticsCommand}"/>
          </TreeViewItem.Header>
        </TreeViewItem>
      </TreeViewItem>
    </TreeView>
  </Grid>
</Page>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...