Search code examples
c#wpfxamldata-bindingcaliburn.micro

Binding an Action to an Checkbox Checked event inside a MenuItem template


I'm currently trying to create a MediaPlayer using Caliburn.Micro. In my ShellView I have a Menu with MenuItems for 'File', 'Edit' and 'Categories'. The Categories MenuItem has List<CategoryModel> as ItemSource. The MenuItem has a ItemTemplate which is set to a Checkbox.

<Menu DockPanel.Dock="Top">
        <MenuItem Header="_File">
            <MenuItem Header="_Close" x:Name="Close"/>
        </MenuItem>
        <MenuItem Header="Edit">
            <MenuItem Header="Settings"/>
            <MenuItem Header="MediaData"/>
            <Separator/>
            <MenuItem Header="Reset"/>
        </MenuItem>
        <MenuItem Header="Categories" ItemsSource="{Binding AvailableCategories}">
            <MenuItem.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding DisplayText}" cal:Message.Attach="[Event Checked] = [Action ChangeSelectedPlaylist($dataContext)]"/>
                </DataTemplate>
            </MenuItem.ItemTemplate>
        </MenuItem>
    </Menu>

Now I want Caliburn to call a Method inside my ShellViewModel. But it always says it's unable to find the target for method ChangeSelectedPlaylist.

Now I've read about Visual Trees and caliburns 'TargetWithoutContext' but I cannot get it to run the Method specified.

All the examples I've found are using ContextMenus and ItemsControl. Which doesn't seem work with Checkboxes inside MenuItems.


Solution

  • Since you have ChangeSelectedPlaylist method defined in ShellViewModel, you should use TargetWithoutContext with binding to the element, where ShellViewModel is set as DataContext. If it's a Window, the xaml should be something like that

    <DataTemplate>
         <CheckBox Content="{Binding DisplayText}" 
                   cal:Message.Attach="ChangeSelectedPlaylist($datacontext)"
                   cal:Action.TargetWithoutContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
    </DataTemplate>