有没有办法以XAML样式附加事件?

时间:2009-10-14 15:00:36

标签: events xaml styles

我希望每个可点击的TreeViewItem都能执行TreeViewItem_MouseLeftButtonDown,有没有办法将它放在样式中,所以我不必在任何地方定义它。我可以在代码中遇到所有孩子,但我认为有一种更简单的方式来做一个风格。

以下代码告诉我:

  

找不到样式属性   'PreviewMouseLeftButtonDown'上   类型   'System.Windows.Controls.TreeViewItem'。

<Window x:Class="TestClickTree2343.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    WindowStartupLocation="CenterScreen"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsExpanded" Value="True" />
            <Setter Property="Foreground" Value="#aaa" />
        </Style>
        <Style x:Key="TreeViewItemClickableStyle" TargetType="TreeViewItem">
            <Setter Property="Cursor" Value="Hand" />
            <Setter Property="Foreground" Value="#000" />
            <Setter Property="PreviewMouseLeftButtonDown" Value="TreeViewItem_MouseLeftButtonDown" />
        </Style>
    </Window.Resources>

    <StackPanel>
        <TreeViewItem Header="Files">
            <TreeViewItem Header="File 1">
                <TreeViewItem Header="Part 1">
                    <TreeViewItem Style="{StaticResource TreeViewItemClickableStyle}" Header="Paragraph 1"/>
                    <TreeViewItem Header="Paragraph 2"/>
                </TreeViewItem>
            </TreeViewItem>
        </TreeViewItem>
    </StackPanel>
</Window>

1 个答案:

答案 0 :(得分:0)

在TreeView中使用SelectedItemChanged:

<强> XAML:

<TreeView  SelectedItemChanged="TreeView_SelectedItemChanged" BorderThickness="0">
    <TreeViewItem 
        Tag="File1" 
        Style="{StaticResource TreeViewItemClickableStyle}" 
        Header="File 1">

        <TreeViewItem Header="Part 1">

            <TreeViewItem Header="Paragraph 1"/>

            <TreeViewItem 
                Tag="Paragraph1" 
                Style="{StaticResource TreeViewItemClickableStyle}" 
                Header="Paragraph 2"/>

            <TreeViewItem Header="Paragraph 3"/>
            <TreeViewItem Header="Paragraph 4"/>
            <TreeViewItem Header="Paragraph 5"/>

        </TreeViewItem>
    </TreeViewItem>
</TreeView>

<强>代码隐藏:

private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    TreeViewItem treeViewItem = ((TreeView)sender).SelectedItem as TreeViewItem;
    if (treeViewItem.Tag != null)
    {
        string tag = treeViewItem.Tag.ToString();
        MessageBox.Show(String.Format("You clicked the tree item: {0}", tag));
    }
}