Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从子xaml检索treeviewitem的datacontext_C#_Wpf_Xaml_Treeview_Datacontext - Fatal编程技术网

C# 从子xaml检索treeviewitem的datacontext

C# 从子xaml检索treeviewitem的datacontext,c#,wpf,xaml,treeview,datacontext,C#,Wpf,Xaml,Treeview,Datacontext,我有一个数据绑定的treeview,从中创建/显示treeview项,并具有上下文菜单。这工作正常。然后,我尝试使用一个自定义的menuitem类,这样就可以通过从contextmenu触发的命令检索treevieItem的datacontext。抱歉,这让人困惑。我可能做得不对 这是我的xaml <UserControl x:Class="Pipeline_General.Custom_Controls.ProjectTree" xmlns="http://schema

我有一个数据绑定的treeview,从中创建/显示treeview项,并具有上下文菜单。这工作正常。然后,我尝试使用一个自定义的menuitem类,这样就可以通过从contextmenu触发的命令检索treevieItem的datacontext。抱歉,这让人困惑。我可能做得不对

这是我的xaml

<UserControl x:Class="Pipeline_General.Custom_Controls.ProjectTree"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:pm="clr-namespace:Pipeline_General"
         mc:Ignorable="d" 
         DataContext = "{Binding RelativeSource={RelativeSource Self}}"
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <TreeView Name="StructureTree" Background="{x:Static pm:myBrushes.defaultBG}" ItemsSource="{Binding ProjectList}">
        <TreeView.ItemContainerStyle>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="IsExpanded" Value="True"/>
                <Setter Property="Margin" Value="5,5,5,5" />
                <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu Background="{x:Static pm:myBrushes.defaultBG}" Foreground="{x:Static pm:myBrushes.gray}">
                            <pm:ProjectTreeMenuItem Header="Add Episode.." 
                                    Element="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"
                                      Command="{x:Static pm:MyCommands.AddEpCommand}" 
                                      CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                      Margin="20,0"/>
                            <pm:ProjectTreeMenuItem Header="Add Sequence.." 
                                      Element="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"
                                      Command="{x:Static pm:MyCommands.AddSeqCommand}" 
                                      CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                      Margin="20,0"/>
                            <pm:ProjectTreeMenuItem Header="Add Scene.." 
                                        Element="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"
                                      Command="{x:Static pm:MyCommands.AddScCommand}" 
                                      CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                      Margin="20,0"/>
                        </ContextMenu>
                    </Setter.Value>
                </Setter>
            </Style>
        </TreeView.ItemContainerStyle>
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate DataType="{x:Type pm:ProjectRoot}" ItemsSource="{Binding Episodes}">
                <TextBlock Text="{Binding Path=Title}" Foreground="{x:Static pm:myBrushes.pink}"
                           FontFamily="Calibri" FontSize="18"/>
                <HierarchicalDataTemplate.ItemContainerStyle>
                    <Style TargetType="{x:Type TreeViewItem}">
                        <Setter Property="IsExpanded" Value="True"/>
                        <Setter Property="Margin" Value="5,5,5,5" />
                        <Setter Property="ContextMenu">
                            <Setter.Value>
                                <ContextMenu Background="{x:Static pm:myBrushes.defaultBG}" Foreground="{x:Static pm:myBrushes.gray}">
                                    <pm:ProjectTreeMenuItem Header="Add Sequence.."  
                                     Element="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"
                                     Command="{x:Static pm:MyCommands.AddSeqCommand}" 
                                      CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                      Margin="20,0"/>
                                    <pm:ProjectTreeMenuItem Header="Add Scene.."
                                      Element="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"
                                      Command="{x:Static pm:MyCommands.AddScCommand}" 
                                      CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                      Margin="20,0"/>
                                    <Separator Height="15" Margin="20,0"/>
                                    <pm:ProjectTreeMenuItem Header="Cut" 
                                    Element="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"
                                    Command="{x:Static pm:MyCommands.CutCommand}" 
                                      CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                      Margin="20,0"/>
                                    <pm:ProjectTreeMenuItem Header="Un-Cut" 
                                    Element="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"
                                    Command="{x:Static pm:MyCommands.UnCutCommand}" 
                                      CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                      Margin="20,0"/>
                                </ContextMenu>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </HierarchicalDataTemplate.ItemContainerStyle>


                <HierarchicalDataTemplate.ItemTemplate>
                    <HierarchicalDataTemplate DataType="{x:Type pm:Episode}" ItemsSource="{Binding Sequences}">
                        <TextBlock Text="{Binding Path=Key}" Foreground="{x:Static pm:myBrushes.yellow}"
                                           FontFamily="Calibri" FontSize="14"/>
                        <HierarchicalDataTemplate.ItemContainerStyle>
                            <Style TargetType="{x:Type TreeViewItem}">
                                <Setter Property="IsExpanded" Value="True"/>
                                <Setter Property="Margin" Value="5,5,5,5" />
                                <Setter Property="ContextMenu">
                                    <Setter.Value>
                                        <ContextMenu Background="{x:Static pm:myBrushes.defaultBG}" Foreground="{x:Static pm:myBrushes.gray}">
                                            <pm:ProjectTreeMenuItem Header="Add Scene.." 
                                             Element="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"
                                             Command="{x:Static pm:MyCommands.AddScCommand}" 
                                            CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                            Margin="20,0"/>
                                            <Separator Height="15" Margin="20,0"/>
                                            <pm:ProjectTreeMenuItem Header="Cut" 
                                            Element="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"
                                            Command="{x:Static pm:MyCommands.CutCommand}" 
                                            CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                            Margin="20,0"/>
                                            <pm:ProjectTreeMenuItem Header="Un-Cut" 
                                             Element="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"
                                            Command="{x:Static pm:MyCommands.UnCutCommand}" 
                                            CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                             Margin="20,0"/>
                                        </ContextMenu>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </HierarchicalDataTemplate.ItemContainerStyle>

                        <HierarchicalDataTemplate.ItemTemplate>
                            <HierarchicalDataTemplate DataType="{x:Type pm:Sequence}" ItemsSource="{Binding Scenes}">
                                <TextBlock Text="{Binding Path=Key}" Foreground="{x:Static pm:myBrushes.yellow}"
                                           FontFamily="Calibri" FontSize="14"/>
                                <HierarchicalDataTemplate.ItemContainerStyle>
                                    <Style TargetType="{x:Type TreeViewItem}">
                                        <Setter Property="ContextMenu">
                                            <Setter.Value>
                                                <ContextMenu Background="{x:Static pm:myBrushes.defaultBG}" Foreground="{x:Static pm:myBrushes.gray}">
                                                    <pm:ProjectTreeMenuItem Header="Cut" 
                                                        Element="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"
                                                        Command="{x:Static pm:MyCommands.CutCommand}" 
                                                        CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                                        Margin="20,0"/>
                                                    <pm:ProjectTreeMenuItem Header="Un-Cut" 
                                                         Element="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}"
                                                        Command="{x:Static pm:MyCommands.UnCutCommand}" 
                                                        CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                                         Margin="20,0"/>
                                                </ContextMenu>
                                            </Setter.Value>
                                        </Setter>
                                    </Style>
                                </HierarchicalDataTemplate.ItemContainerStyle>
                            </HierarchicalDataTemplate>
                        </HierarchicalDataTemplate.ItemTemplate>
                    </HierarchicalDataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</Grid>

以及我的自定义菜单项类和命令

public static class MyCommands
{
    static MyCommands()
    {
        AddEpCommand = new SimpleDelegateCommand(p =>
        {
            var menuItem = p as ProjectTreeMenuItem;
            var Element = menuItem.Element as ProjectElement;
            Console.WriteLine(Element.Key);
            Console.WriteLine("EP");
        });

        AddSeqCommand = new SimpleDelegateCommand(p =>
        {
            var menuItem = p as ProjectTreeMenuItem;
            var Element = menuItem.Element as ProjectElement;
            Console.WriteLine(Element.Key);
            Console.WriteLine("SEQ");
        });

        AddScCommand = new SimpleDelegateCommand(p =>
        {
            var menuItem = p as ProjectTreeMenuItem;
            var Element = menuItem.Element as ProjectElement;
            Console.WriteLine(Element.Key);
            Console.WriteLine("SC");
        });

        CutCommand = new SimpleDelegateCommand(p =>
        {
            var menuItem = p as ProjectTreeMenuItem;
            var Element = menuItem.Element as ProjectElement;
            Console.WriteLine(Element.Key);
            Console.WriteLine("SC");
        });

        UnCutCommand = new SimpleDelegateCommand(p =>
        {
            var menuItem = p as ProjectTreeMenuItem;
            var Element = menuItem.Element as ProjectElement;
            Console.WriteLine(Element.Key);
            Console.WriteLine("SC");
        });
    }

    public static ICommand AddEpCommand { get; set; }
    public static ICommand AddSeqCommand { get; set; }
    public static ICommand AddScCommand { get; set; }
    public static ICommand CutCommand { get; set; }
    public static ICommand UnCutCommand { get; set; }
}

public class SimpleDelegateCommand : ICommand
{
    public SimpleDelegateCommand(Action<object> executeAction)
    {
        _executeAction = executeAction;
    }

    private Action<object> _executeAction;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _executeAction(parameter);
    }
}

public class ProjectTreeMenuItem : MenuItem
{
    #region Element (DependencyProperty)
    public ProjectElement Element
    {
        get { return (ProjectElement)GetValue(ElementProperty); }
        set { SetValue(ElementProperty, value); }
    }
    public static readonly DependencyProperty ElementProperty =
        DependencyProperty.Register("Element", typeof(ProjectElement), typeof(ProjectTreeMenuItem),
          new PropertyMetadata { PropertyChangedCallback = ElementChanged });
    private static void ElementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ProjectTreeMenuItem so = d as ProjectTreeMenuItem;
        if (so != null && e.NewValue != null)
        {
            so.Element = (ProjectElement)e.NewValue;
            Console.WriteLine("HERE " + so.Element.Title);
        }
    }
    #endregion

    public ProjectTreeMenuItem()
        :base()
    {

    }
}
公共静态类MyCommands
{
静态MyCommands()
{
AddEpCommand=新的SimpleDelegateCommand(p=>
{
var menuItem=p作为项目树menuItem;
var Element=menuItem.Element作为ProjectElement;
Console.WriteLine(Element.Key);
控制台写入线(“EP”);
});
AddSeqCommand=新的SimpleDelegateCommand(p=>
{
var menuItem=p作为项目树menuItem;
var Element=menuItem.Element作为ProjectElement;
Console.WriteLine(Element.Key);
控制台写入线(“SEQ”);
});
AddScCommand=新的SimpleDelegateCommand(p=>
{
var menuItem=p作为项目树menuItem;
var Element=menuItem.Element作为ProjectElement;
Console.WriteLine(Element.Key);
控制台写入线(“SC”);
});
CUTCOMAND=新的SimpleDelegateCommand(p=>
{
var menuItem=p作为项目树menuItem;
var Element=menuItem.Element作为ProjectElement;
Console.WriteLine(Element.Key);
控制台写入线(“SC”);
});
UNUCTCOMAND=新的SimpleDelegateCommand(p=>
{
var menuItem=p作为项目树menuItem;
var Element=menuItem.Element作为ProjectElement;
Console.WriteLine(Element.Key);
控制台写入线(“SC”);
});
}
公共静态ICommand AddEpCommand{get;set;}
公共静态ICommand addSeq命令{get;set;}
公共静态ICommand AddScCommand{get;set;}
公共静态ICommand命令{get;set;}
公共静态ICOMAND UNCUTCOMAND{get;set;}
}
公共类SimpleDelegateCommand:ICommand
{
公共SimpleDelegateCommand(操作执行)
{
_executeAction=executeAction;
}
私人行动——执行;
公共布尔CanExecute(对象参数)
{
返回true;
}
公共事件处理程序CanExecuteChanged;
public void Execute(对象参数)
{
_执行(参数);
}
}
公共类ProjectTreeMenuItem:MenuItem
{
#区域元素(从属属性)
公共项目元素
{
获取{return(ProjectElement)GetValue(ElementProperty);}
set{SetValue(ElementProperty,value);}
}
公共静态只读DependencyProperty ElementProperty=
DependencyProperty.Register(“元素”)、typeof(项目元素)、typeof(项目树元素),
新属性元数据{PropertyChangedCallback=ElementChanged});
私有静态void元素已更改(DependencyObject d、DependencyPropertyChangedEventArgs e)
{
ProjectTreeMenuItem so=d作为ProjectTreeMenuItem;
if(so!=null&&e.NewValue!=null)
{
元素=(ProjectElement)e.NewValue;
Console.WriteLine(“此处”+so.Element.Title);
}
}
#端区
公共项目树元素()
:base()
{
}
}
projectElement类(我在项目的数百个其他地方使用)有一个String键,String Title属性,在其他地方可以正常工作。我很确定我的问题在于通过xaml通过datac设置元素属性
                          <ContextMenu Background="{x:Static pm:myBrushes.defaultBG}" Foreground="{x:Static pm:myBrushes.gray}"
                                     DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}">
                            <MenuItem Header="Add Episode.." 
                                      Command="{x:Static pm:MyCommands.AddEpCommand}" 
                                      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,
                                            AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.DataContext}"
                                      Margin="20,0"/>
                            <MenuItem Header="Add Sequence.." 
                                      Command="{x:Static pm:MyCommands.AddSeqCommand}" 
                                      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,
                                            AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.DataContext}"
                                      Margin="20,0"/>
                            <MenuItem Header="Add Scene.." 
                                      Command="{x:Static pm:MyCommands.AddScCommand}" 
                                      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,
                                            AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.DataContext}"
                                      Margin="20,0"/>
                        </ContextMenu>