C#WPF Treeview ItemContainerStyle使鼠标点击事件发送者失去TreeviewItem引用

时间:2018-05-15 06:08:58

标签: c# wpf treeview

我有这个有效的代码,

    private void TreeSetup_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (sender is TreeViewItem)
        {
            ((TreeViewItem)sender).IsSelected = true;
        }
        e.Handled = true;
    }

    private void TreeSetup_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
            ContextMenu PopupMenu = this.FindResource("cmButton") as ContextMenu;
            if (TreeSetup.SelectedItem != null)
            {
                PopupMenu.PlacementTarget = sender as TreeViewItem;
                PopupMenu.IsOpen = true;
        }
    }

但是一旦我添加了这个ItemContainerStyle,

 <TreeView.ItemContainerStyle>
                        <Style TargetType="{x:Type TreeViewItem}">
                            <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}" />
                            <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
                            <Style.Triggers>
                                <Trigger Property="IsSelected" Value="True">
                                    <Setter Property="FontWeight" Value="Bold" />
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </TreeView.ItemContainerStyle>

鼠标按下事件的发件人变为TreeView而不是TreeViewItem。 有谁知道原因并解决这个问题?

1 个答案:

答案 0 :(得分:0)

我在ItemContainerStyle:

下绑定了mousedown事件
 <TreeView.ItemContainerStyle>
                        <Style TargetType="TreeViewItem">
                            <EventSetter Event="MouseRightButtonDown" Handler="TreeSetup_MouseRightButtonDown"/>
                            <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}" />
                            <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
                            <Style.Triggers>
                                <Trigger Property="IsSelected" Value="True">
                                    <Setter Property="FontWeight" Value="Bold" />
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </TreeView.ItemContainerStyle>