首页 > 解决方案 > 如何在一个 Grid 上创建 DialogHost 并在另一个 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.

有可能这样做吗?如果是这样,怎么做?

标签: c#.netwpfxamlmaterial-design-in-xaml

解决方案


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

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

由于此机制通过搜索对话主机来工作,因此您必须将视图分配为它的内容。这意味着将您的Grid内部DialogHost标签移到DialogContent.

对于您的情况,您可以将DialogHost直接放入窗口或您的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>

推荐阅读