【问题标题】:WPF window style applied to wrong windowsWPF 窗口样式应用于错误的窗口
【发布时间】:2019-12-13 16:44:27
【问题描述】:

我已经为这样的对话框创建了自定义窗口类:

public class DialogBase : Window
{
  // common stuff here
}

public class DialogOkCancel : DialogBase
{
        static DialogOkCancel()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(DialogOkCancel), 
                 new FrameworkPropertyMetadata(typeof(DialogOkCancel)));
        }
        // specific stuff here
}

样式看起来像这样,并且包含特定于对话框的内容,例如标题栏、确定/取消按钮等。

<Style x:Key="DialogBaseStyle" TargetType="{x:Type base:DialogBase}" BasedOn="{StaticResource {x:Type Window}}">
  <Setter Property="ShowInTaskbar" Value="False"/>
  <!-- more stuff here -->
</Style>

<Style TargetType="{x:Type base:DialogOkCancel}" BasedOn="{StaticResource DialogBaseStyle}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type base:DialogOkCancel}">
                <!-- more stuff here -->
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

这在运行时工作得非常好。此外,对话框在 XAML 设计器中显示良好。

但是,在 XAML 设计器中,DialogOkCancel 样式也会应用于其他所有其他窗口,例如应用程序主窗口(它只是从普通的 Window 派生的)。标题栏、按钮和一切。我真的不明白这一点,因为TargetType 是特定的。这不会在运行时发生。

我在这里没有看到什么?

【问题讨论】:

  • 可能是 XAML 设计器中的错误...
  • 这件事一直发生在我身上,我的解决方案是我只是把键放在样式上并将其添加到特定的窗口。由于某些奇怪的原因,当您拥有“BasedOn”属性并且它指向某些基本控件时,XAML 设计器会很困惑!
  • @J.Memisevic 我希望避免基于键的样式以避免重复。但是,是的,我认为这是最后的手段。

标签: c# wpf xaml


【解决方案1】:

在设计器模式和运行时应用样式的正确方法是在App.xaml 中声明样式。最佳做法是拥有一个 MergedDictionaries,其中包含各种样式字典的引用,这些字典将位于其他文件中。

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- Converters -->
            <ResourceDictionary Source="Resources/Converters.xaml"/>
            <!-- Windows -->
            <ResourceDictionary Source="Resources/WindowStyles.xaml"/>
            // ... and all others //

WindowStyles.xaml 可以包含您在上面编写的确切样式。它们将应用于设计器和运行时中的所有 DialogOkCancel 窗口。

希望有所帮助。

【讨论】:

  • 我的样式已经在字典中,并在 App.xaml 中合并。你没有理解我的问题。样式应用于我的对话框类,问题是它们也被应用于不从 DialogBase 继承的其他窗口。
  • 那你为什么要为 DialogOkCancel 使用静态构造函数来覆盖样式呢?一旦你在 App.xaml 中声明它们,就不需要了。它们应该在设计器模式和运行时工作。
猜你喜欢
  • 1970-01-01
  • 2017-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多