Dynamic menus with Caliburn micro

回眸只為那壹抹淺笑 提交于 2019-12-06 06:52:59

问题


I use Caliburn micro for my WPF Project. Static menus are easy to bind with Caliburn

<Menu Grid.Row="0" IsMainMenu="True">
    <MenuItem Header="_File">
        <MenuItem x:Name="OpenScript" Header="_Open script"/>
    </MenuItem>
    <MenuItem Header="_Script">
        <MenuItem x:Name="RunScript" Header="_Run script" />
        <MenuItem x:Name="StopScript" Header="_Stop script" />
    </MenuItem>
    <MenuItem Header="S_ettings">
        <MenuItem x:Name="Plugins" Header="_Plugins">...Clickable children here</MenuItem>
    </MenuItem>
</Menu>  

The names are bound to methods on the model, but for the Plugins menu that you see above we need to bind against a collection of PluginViewModel.. Then when you click a plugin i want a Caliburn action method to trigger on the menu view model (You now the kind that you can yield reuturn IResults from).. Is this possible?

This question is for this open source project https://github.com/AndersMalmgren/FreePIE

edit: Forgot to mentioned that i have solved the binding part,

public BindableCollection<PluginMenuViewModel> Plugins { get; set; }

But i do not know how to listen to the click from the model


回答1:


The best way is to add your own message binder

MessageBinder.SpecialValues.Add("$originalsourcecontext", context => {
    var args = context.EventArgs as RoutedEventArgs;
    if(args == null) {
        return null;
    }

    var fe = args.OriginalSource as FrameworkElement;
    if(fe == null) {
        return null;
    }

    return fe.DataContext;
});

You can then use it from xaml like this

cal:Message.Attach="ShowSettings($originalsourcecontext)"



回答2:


(sorry for my bad english)

You can call a especific method on your VM using the syntax (on your XAML):

cal:Message.Attach="[Event SelectionChanged] = [Action ItemClick($this)]"

This will call a ItemClick method on the VM passing the bounded item itself as parameter. If this is a "PluginItem" with an execute method (like normally is), inside that method you just need to call it:

    public void ItemClick(PluginItem item)
    {
        item.Execute();
    }

You can read more about Actions here: http://caliburnmicro.codeplex.com/wikipage?title=All%20About%20Actions&referringTitle=Documentation



来源:https://stackoverflow.com/questions/8988705/dynamic-menus-with-caliburn-micro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!