MenuItem Command not executing when defined through a style inside a ContextMenu

I am trying to create a file tree using a TreeView where I can bind a collection to. In order to bind to a TreeView you need to use a HierarchicalDataTemplate. This automatically uses the default TreeViewItem as its base. But I have no direct access to this TreeViewItem to add stuff to. This is why I am accessing the properties of this TreeViewItem using a style and setters.

Now when I add a ContextMenu through this style, all the commands and events that are assigned to the MenuItems won’t fire. The ContextMenu still shows up fine when I right click the MenuItem.

<TreeView ItemsSource="{Binding FileTree}">
    <TreeView.Resources>
        <Style TargetType="{x:Type TreeViewItem}" BasedOn="{StaticResource {x:Type TreeViewItem}}">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu Width="250">
                        <!-- This command never gets executed when the menu item is clicked -->
                        <MenuItem Header="New File" Command="{Binding NewFile}" />
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
    </TreeView.Resources>
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type model:FileTreeModel}"
                                  ItemsSource="{Binding Path=Children}">
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding FileName, Converter={StaticResource FileNameToIconConverter}}"
                        Width="14" Height="12" Margin="5,0,5,0" SnapsToDevicePixels="True"
                        Stretch="Fill" />
                <TextBlock Text="{Binding Path=FileName}" />
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>
public class FileTreeModel
{
    public string? FileName { get; set; }
    public string? Path { get; set; }
    public IList<FileTreeModel> Children { get; set; } = [];
}
public ObservableCollection<FileTreeModel> FileTree { get; }
public ICommand NewFile { get; }

public ExplorerViewModel(INewFileService newFileService)
{
    FileTree = [];
    NewFile = new RelayCommand(() =>
    {
        Console.WriteLine("New file"); // Never gets ran
        newFileService.NewFile();
    });
}

4

Without knowing how you set the Data Context, it is impossible to give an exact answer to your question.

One of the possible variants:

<Window -------------------
        -------------------
        DataContext="{DynamicResource vm}">
    <Window.Resources>
        <local:FilesTreeViewModel x:Key="vm"/>
    </Window.Resources>


    ----------------------------

                    <ContextMenu Width="250">
                        <!-- This command never gets executed when the menu item is clicked -->
                        <MenuItem Header="New File"
                                  Command="{Binding NewFile, Source={StaticResource vm}}"/>
                    </ContextMenu>


    ----------------------------

The solution I have found was changing TreeView.Resources to TreeView.ItemContainerStyle. This means it will now try to find the command inside the container model, instead of the view model. This is a very hacky solution, and I would still like to figure out a way that allows me to have the command inside the view model.

<TreeView ItemsSource="{Binding FileTree}">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}" BasedOn="{StaticResource {x:Type TreeViewItem}}">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu Width="250">
                        <!-- It will now try to find the NewFile command inside FileTreeModel, because of ItemContainerStyle -->
                        <MenuItem Header="New File" Command="{Binding NewFile}" />
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
    </TreeView.ItemContainerStyle>
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type model:FileTreeModel}"
                                  ItemsSource="{Binding Path=Children}">
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding FileName, Converter={StaticResource FileNameToIconConverter}}"
                        Width="14" Height="12" Margin="5,0,5,0" SnapsToDevicePixels="True"
                        Stretch="Fill" />
                <TextBlock Text="{Binding Path=FileName}" />
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>
public class FileTreeModel
{
    public string? FileName { get; set; }
    public string? Path { get; set; }
    public IList<FileTreeModel> Children { get; set; } = [];

    public ICommand NewFileCommand { get; }

    public FileTreeModel()
    {
        NewFile = new RelayCommand(() =>
        {
            Console.WriteLine("New file");
        });
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật