如何在一个网格上创建 DialogHost 并在另一个网格上调用

How to create DialogHost on one Grid and call on another Grid

我正在寻找一种方法使我的 DialogHost 居中于 WPF 应用程序的中间,为此我需要在 MainGrid.

中创建它
<Grid Name="MainGrid">
    <materialDesign:DialogHost CloseOnClickAway="True">
       <materialDesign:DialogHost.DialogContent>
           <Grid Margin="20">
               <TextBlock Text="My first Dialog" />
           </Grid>
       </materialDesign:DialogHost.DialogContent>
   </materialDesign:DialogHost>
   
    <Grid Name="Grid1" Width="250" Height ="Auto">
        ... //MyCode
        <Button Name="MyButton" Style="{StaticResource MaterialDesignRaisedButton}" Click="ButtonClick">
        ...
    </Grid>
</Grid>

但是,我将用来调用此 DialogHost 的按钮位于 Grid1

可以吗?如果是,怎么做?

您可以使用Material Design 提供的DialogHost.OpenDialogCommand 路由命令。如果您将它作为 Command 分配给您的按钮,它将引发一个路由事件,该事件在可视化树中冒泡,直到到达通过显示对话框处理它的 DialogHost。例如:

<Button Command="{x:Static materialDesign:DialogHost.OpenDialogCommand}">

由于此机制通过搜索 parent 对话主机来工作,因此您必须分配给它的 views as content。这意味着在 DialogContent.

之后将 Grid 移动到 DialogHost 标签内

对于您的情况,您可以将 DialogHost 直接放入 window 或 MainGrid 并将 Grid1 放入对话主机内容。最后,您只需将 OpenDialogCommand 分配给按钮即可。

<Window ...>
   <Grid Name="MainGrid">
      <materialDesign:DialogHost CloseOnClickAway="True">
         <materialDesign:DialogHost.DialogContent>
            <Grid Margin="20">
               <TextBlock Text="My first Dialog" />
            </Grid>
         </materialDesign:DialogHost.DialogContent>
         <Grid Name="Grid1" Width="250" Height ="Auto">
            <Button Name="MyButton"
                    Style="{StaticResource MaterialDesignRaisedButton}"
                    Command="{x:Static materialDesign:DialogHost.OpenDialogCommand}">
         </Grid>
      </materialDesign:DialogHost>
   </Grid>
</Window>