【问题标题】:Can a user control style its parent window?用户控件可以设置其父窗口的样式吗?
【发布时间】:2019-11-20 21:03:40
【问题描述】:

我有一个使用 Prism 的PopupWindowAction 在弹出对话框中显示的用户控件。我不希望窗口可调整大小。是否可以从用户控件设置此窗口的样式?我试图用这个:

<UserControl.Resources>
    <Style x:Key="WindowStyle" TargetType="{x:Type Window}">
        <Setter Property="ResizeMode" Value="NoResize" />
    </Style>
</UserControl.Resources>

但它不起作用。

编辑:

根据接受的答案,我将样式移至定义IteractionRequestTrigger 并分配PopupWindowActionWindowStyle 的用户控件。

调用使用控件的新代码:

添加资源

<UserControl.Resources>
    <Style x:Key="WindowStyle" TargetType="Window">
        <Setter Property="ResizeMode" Value="NoResize" />
        <Setter Property="SizeToContent" Value="WidthAndHeight" />
    </Style>
</UserControl.Resources>

弹窗声明

<prism:InteractionRequestTrigger SourceObject="{Binding InteractionRequest}">
    <prism:PopupWindowAction WindowStyle="{StaticResource WindowStyle}">                
        <prism:PopupWindowAction.WindowContent>
            <sharedV:InformationDialog />
        </prism:PopupWindowAction.WindowContent>
    </prism:PopupWindowAction>
</prism:InteractionRequestTrigger>

【问题讨论】:

  • 为什么不在窗口本身设置ResizeMode
  • 很高兴知道为什么这被否决了。

标签: wpf xaml prism


【解决方案1】:

您的 XAML 不起作用的原因是:

  • 您创建的样式是明确的 - 它有一个x:Key。显式样式必须直接应用于目标元素&lt;Window Style="{StaticResource WindowStyle}" ... /&gt;
  • 即使您删除 x:Key 并使其成为隐式样式,因为它是在 UserControl 的资源中定义的,它也只会应用于树中 UserControl 下方的项目。

在这种情况下,您可能需要查看PopupWindowActionWindowStyle 属性。您应该可以在那里设置样式。

【讨论】:

  • WindowStyle 完美运行。非常感谢。
【解决方案2】:

孩子不能直接改变他们父母的风格,因为视觉树模型被设计为从广泛到具体(WindowUserControl...),风格在那个方向被继承和覆盖。也就是说,一切皆有可能,因为一切都只是代码!

这不是一个好方法,但是您可以在后面的代码中使用UserControlLoaded 方法来完成导航可视化树以查找父级Window 并强制执行的工作设置ResizeMode 属性。您可以使用this.Parent 执行此操作并检查is Window 何时为真,或者您可以使用VisualTreeHelper.GetParent

XAML:

<UserControl Loaded="OnLoaded"></UserControl>

C#:

private void OnLoaded(object sender, RoutedEventArgs e)
{
    var currentParent = Parent;

    while (currentParent != null && !(currentParent is Window))
    {
        currentParent = VisualTreeHelper.GetParent(currentParent);
    }

    if (currentParent is Window parentWindow)
    {
        parentWindow.ResizeMode = ResizeMode.NoResize;
    }
}

【讨论】:

  • 我在想答案应该是这样的。我会试一试。感谢您的帮助。
  • 我选择了没有代码的答案,但是因为我确信这会起作用,所以我给了你一个赞成票。
猜你喜欢
  • 2016-05-10
  • 1970-01-01
  • 2011-03-08
  • 2011-04-16
  • 2010-10-07
  • 1970-01-01
  • 2016-07-05
  • 1970-01-01
  • 2018-01-27
相关资源
最近更新 更多