前言:

最初是想解答园友“ ”的,后来想举一反三,将这个问题简单剖析下,做到知其所以然。

materialdesigninxaml 控件库高度封装,有一些控件在使用过程中有隐晦前提条件,使用前还得多读读源码。

针对这个问题,我分步骤说明一下解决思路。

1.首先解释下“无法绑定到目标方法,因其签名或安全透明度与委托类型的签名或安全透明度不兼容”异常。字面看是提示有属性绑定失败,而且提到是委托类型,由此需检查哪些属性是绑定到委托类型的。

dialogopenedattached、dialogclosingattached是dialoghost控件的两个附件属性,官方示例是绑定到combineddialogopenedeventhandler、combineddialogclosingeventhandler上,这两个事件处理函数是需要我们在后置代码中去定义的。我们可以在这两个事件处理函数中添加一些自定义逻辑。

public void combineddialogopenedeventhandler(object sender, dialogopenedeventargs eventargs)
{
    combinedcalendar.selecteddate = _mainviewmodel.date;
    combinedclock.time = _mainviewmodel.time;
}

public void combineddialogclosingeventhandler(object sender, dialogclosingeventargs eventargs)
{
    if (convert.toboolean(convert.touint16(eventargs.parameter)) && combinedcalendar.selecteddate is datetime selecteddate)
    {
        datetime combined = selecteddate.addseconds(combinedclock.time.timeofday.totalseconds);
        _mainviewmodel.time = combined;
        _mainviewmodel.date = combined;
    }
}

编译不再报错,这样最直接的问题就解决了。

2.接下来还会遇到一个问题,就是弹出时间选择器对话框的按钮是禁用状态。

这个问题在控件github主页的wiki中有详细解答,issues中也有相关问题。

翻译如下:

  1. 第一种类型是一个简单的icommand实现,通过视图模型(或类似的)提供。这些命令在执行时通常只是调用一个方法。尽管wpf并没有为此提供一个本地实现,但许多流行的mvvm库确实有一些icommand接口的实现,旨在使方法调用变得简单。
  2. 路由命令的设置是为了明确地在调用命令的元素和处理命令执行的元素之间造成分离。当一个路由命令被调用时,wpf通过可视化树(从调用命令的元素开始)寻找一个可以处理该命令的元素。如果没有找到处理程序,那么该命令将导致该按钮被禁用。在dialoghost.opendialogcommand的例子中,这种情况经常发生,因为在视觉树中没有找到dialoghost实例。你也可以通过使用commandtarget属性来指定另一个命令目标,以找到routedcommand的处理程序。

根本原因就是“因为在视觉树中没有找到dialoghost实例”。这就是隐晦前提条件。

github主页的wiki中介绍了打开对话框的4种方式,分别如下:

  1. dialoghost.opendialogcommand

    <button command="{x:static md:dialoghost.opendialogcommand}" />
    

    routedcommand 通常从一个按钮中使用,可通过commandparameter提供可选的内容。

  2. dialoghost.isopen

    <md:dialoghost isopen="true" />
    

    依赖属性,可以从xaml触发,从代码后台或通过绑定设置。内容必须在dialoghost.dialogcontent中设置。

  3. dialoghost.show

    dialoghost.show(viewormodel);
    

    基于异步/等待的静态api,可以纯粹地在代码中使用(例如从视图模型中)。内容可以直接传递给对话框。注意,如果你有多个窗口和多个dialoghost实例,你可以设置dialoghost.identifier属性,并向.show(..)方法提供标识符,以帮助找到所需的dialoghost。

    如果有多个可能的对话主机实例,在正确的窗口显示对话框的替代方法是使用扩展方法。

  4. .show() 扩展方法
    该方法同时扩展了window和depedencyobject,将尝试定位最合适的dialoghost来显示对话框。

但文档还漏了一种很实用也很常见的方式,官方的示例就是这种用法。将 mainwindow 的根容器定义为 dialoghost。

<materialdesign:dialoghost dialogtheme="inherit"
                            identifier="rootdialog">
    <!--content-->
</materialdesign:dialoghost>

这样在视觉树中始终能找到dialoghost实例,对于实现弹框全局模态效果,这种方式值得推荐。

代码如下:

<materialdesign:dialoghost dialogtheme="inherit"
                       identifier="rootdialog">
    <grid>
        <stackpanel horizontalalignment="center"
                verticalalignment="center"
                orientation="horizontal">
            <textblock verticalalignment="center"
                   fontsize="24"
                   text="{binding date, stringformat={}{0:yyyy-mm-dd hh:mm:ss}}" />
            <button margin="8 0 0 0"
                materialdesign:dialoghost.dialogclosingattached="combineddialogclosingeventhandler"
                materialdesign:dialoghost.dialogopenedattached="combineddialogopenedeventhandler"
                command="{x:static materialdesign:dialoghost.opendialogcommand}"
                content="...">
                <button.commandparameter>
                    <grid margin="-1">
                        <grid.rowdefinitions>
                            <rowdefinition height="*" />
                            <rowdefinition height="auto" />
                        </grid.rowdefinitions>
                        <stackpanel grid.row="0"
                                orientation="horizontal">
                            <calendar x:name="combinedcalendar"
                                  margin="-1 -4 -1 0" />
                            <materialdesign:clock x:name="combinedclock"
                                              displayautomation="cyclewithseconds"
                                              is24hours="true" />
                        </stackpanel>
                        <stackpanel grid.row="1"
                                margin="8"
                                horizontalalignment="right"
                                orientation="horizontal">
                            <button command="{x:static materialdesign:dialoghost.closedialogcommand}"
                                commandparameter="0"
                                content="cancel"
                                style="{dynamicresource materialdesignflatbutton}" />
                            <button command="{x:static materialdesign:dialoghost.closedialogcommand}"
                                commandparameter="1"
                                content="ok"
                                style="{dynamicresource materialdesignflatbutton}" />
                        </stackpanel>
                    </grid>
                </button.commandparameter>
            </button>
        </stackpanel>
    </grid>
</materialdesign:dialoghost>
3.除了定义dialoghost作为根容器,还可以通过指定commandtarget的来解决。
<grid>
    <stackpanel horizontalalignment="center"
                verticalalignment="center"
                orientation="horizontal">
        <textblock verticalalignment="center"
                   fontsize="24"
                   text="{binding date, stringformat={}{0:yyyy-mm-dd hh:mm:ss}}" />
        <button margin="8 0 0 0"
                materialdesign:dialoghost.dialogclosingattached="combineddialogclosingeventhandler"
                materialdesign:dialoghost.dialogopenedattached="combineddialogopenedeventhandler"
                command="{x:static materialdesign:dialoghost.opendialogcommand}"
                commandtarget="{binding elementname=datepickerdialoghost}"
                content="...">
            <button.commandparameter>
                <grid margin="-1">
                    <grid.rowdefinitions>
                        <rowdefinition height="*" />
                        <rowdefinition height="auto" />
                    </grid.rowdefinitions>

                    <stackpanel grid.row="0"
                                orientation="horizontal">
                        <calendar x:name="combinedcalendar"
                                  margin="-1 -4 -1 0" />

                        <materialdesign:clock x:name="combinedclock"
                                              displayautomation="cyclewithseconds"
                                              is24hours="true" />
                    </stackpanel>

                    <stackpanel grid.row="1"
                                margin="8"
                                horizontalalignment="right"
                                orientation="horizontal">
                        <button command="{x:static materialdesign:dialoghost.closedialogcommand}"
                                commandparameter="0"
                                content="cancel"
                                style="{dynamicresource materialdesignflatbutton}" />

                        <button command="{x:static materialdesign:dialoghost.closedialogcommand}"
                                commandparameter="1"
                                content="ok"
                                style="{dynamicresource materialdesignflatbutton}" />
                    </stackpanel>
                </grid>
            </button.commandparameter>
        </button>
    </stackpanel>

    <materialdesign:dialoghost x:name="datepickerdialoghost">
    </materialdesign:dialoghost>
</grid>

这种方式的content部分是通过commandparameter传递给command的。下面的源代码一目了然。

commandbindings.add(new commandbinding(opendialogcommand, opendialoghandler));

private void opendialoghandler(object sender, executedroutedeventargs executedroutedeventargs)
{
    if (executedroutedeventargs.handled) return;
    if (executedroutedeventargs.originalsource is dependencyobject dependencyobject)
    {
        _attacheddialogopenedeventhandler = getdialogopenedattached(dependencyobject);
        _attacheddialogclosingeventhandler = getdialogclosingattached(dependencyobject);
    }
    if (executedroutedeventargs.parameter != null)
    {
        asserttargetablecontent();
        if (_popupcontentcontrol != null)
        {
            _popupcontentcontrol.datacontext = opendialogcommanddatacontextsource switch
            {
                dialoghostopendialogcommanddatacontextsource.senderelement
                    => (executedroutedeventargs.originalsource as frameworkelement)?.datacontext,
                dialoghostopendialogcommanddatacontextsource.dialoghostinstance => datacontext,
                dialoghostopendialogcommanddatacontextsource.none => null,
                _ => throw new argumentoutofrangeexception(),
            };
        }
        dialogcontent = executedroutedeventargs.parameter;
    }
    setcurrentvalue(isopenproperty, true);
    executedroutedeventargs.handled = true;
}
4.如果不想通过commandparameter传递内容参数,还可以直接在dialogcontent定义内容部分。这是使用dialog控件的常见方式。
<grid>
    <materialdesign:dialoghost>
        <materialdesign:dialoghost.dialogcontent>
            <grid margin="-1">
                <grid.rowdefinitions>
                    <rowdefinition height="*" />
                    <rowdefinition height="auto" />
                </grid.rowdefinitions>

                <stackpanel grid.row="0"
                            orientation="horizontal">
                    <calendar x:name="combinedcalendar"
                              margin="-1 -4 -1 0" />

                    <materialdesign:clock x:name="combinedclock"
                                          displayautomation="cyclewithseconds"
                                          is24hours="true" />
                </stackpanel>

                <stackpanel grid.row="1"
                            margin="8"
                            horizontalalignment="right"
                            orientation="horizontal">
                    <button command="{x:static materialdesign:dialoghost.closedialogcommand}"
                            commandparameter="0"
                            content="cancel"
                            style="{dynamicresource materialdesignflatbutton}" />

                    <button command="{x:static materialdesign:dialoghost.closedialogcommand}"
                            commandparameter="1"
                            content="ok"
                            style="{dynamicresource materialdesignflatbutton}" />
                </stackpanel>
            </grid>
        </materialdesign:dialoghost.dialogcontent>

        <stackpanel horizontalalignment="center"
                    verticalalignment="center"
                    orientation="horizontal">
            <textblock verticalalignment="center"
                       fontsize="24"
                       text="{binding date, stringformat={}{0:yyyy-mm-dd hh:mm:ss}}" />
            <button margin="8 0 0 0"
                    materialdesign:dialoghost.dialogclosingattached="combineddialogclosingeventhandler"
                    materialdesign:dialoghost.dialogopenedattached="combineddialogopenedeventhandler"
                    command="{x:static materialdesign:dialoghost.opendialogcommand}"
                    commandtarget="{binding elementname=datepickerdialoghost}"
                    content="..." />
        </stackpanel>
    </materialdesign:dialoghost>
</grid>

源码下载: github