gpt4 book ai didi

c# - 在 WinForms 中托管时管理 WPF 主题

转载 作者:行者123 更新时间:2023-11-30 12:22:44 24 4
gpt4 key购买 nike

我正在用 WPF 替换旧的 WinForms 应用程序的一部分,希望最终能用它来实现 MVVM 范例。

这项工作给我带来的一个主要问题是在整个应用程序中维护 WinForms 组件使用的动态主题。这些主要是 2007 年和 2010 年旧 Office 主题的集合。

我的计划是构建一个启动 WPF 应用程序的单例对象,为各种控件的颜色添加一个带有 DynamicResource Hook 的资源字典,然后动态换出另一个实际包含颜色定义的资源字典作为托管 WinForms 应用程序更改其主题。

只要 WPF 托管在 WPF 窗口中,它就可以完美运行。如果 WPF 托管在 WinForms 容器中,资源字典肯定会被换出,但 View 不会刷新。我知道这一点,因为一旦我将鼠标悬停在 View 上的按钮上,它的颜色就会更新。

我最近将代码撕成一个独立的解决方案来尝试对其进行测试,因此我将在此处添加它们。此示例代码是一个独立测试,用于在一个简单的 WinForms 项目中更改一次主题:

UserControlResourceDictionary.xaml

<SolidColorBrush x:Key="WhiteBrush" Color="White" />

<!--Region Containers-->

<Style TargetType="{x:Type UserControl}">
<Setter Property="Background" Value="{DynamicResource DefaultBackgroundBrush}"/>
</Style>

<Style TargetType="{x:Type Panel}">
<Setter Property="Background" Value="{DynamicResource DefaultBackgroundBrush}"/>
</Style>

<Style TargetType="{x:Type Grid}" BasedOn="{StaticResource {x:Type Panel}}"/>
<Style TargetType="{x:Type StackPanel}" BasedOn="{StaticResource {x:Type Panel}}"/>

<!--End Region Containers-->

<!--Region TextBox-->

<Style TargetType="{x:Type TextBox}">
<Setter Property="FontSize" Value="11" />
<Setter Property="FontWeight" Value="Normal" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border BorderThickness="1"
BorderBrush="{DynamicResource TextBoxBorderBrush}"
Background="{DynamicResource TextBoxBackgroundBrush}"
x:Name="Border">
<ScrollViewer x:Name="PART_ContentHost" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="Border" Property="Background"
Value="{DynamicResource TextBoxMouseOverBrush}" />
</Trigger>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter TargetName="Border" Property="Background" Value="{DynamicResource TextBoxKeyboardFocusBrush}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<!--End Region TextBox-->

<!--Region Button-->

<Style TargetType="{x:Type Button}">
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="Foreground" Value="{DynamicResource FontColorBrush}" />
<Setter Property="FontSize" Value="11" />
<Setter Property="Width" Value="90" />
<Setter Property="Height" Value="25" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border CornerRadius="{DynamicResource ButtonCornerRadius}"
BorderThickness="1"
BorderBrush="{DynamicResource DefaultButtonBorderBrush}"
Background="{DynamicResource DefaultButtonBrush}"
x:Name="Border">
<ContentPresenter Margin="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
RecognizesAccessKey="True" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="Border" Property="Background"
Value="{DynamicResource DefaultMouseOverBrush}" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="Border" Property="Background" Value="{DynamicResource ButtonPressBrush}" />
<Setter TargetName="Border" Property="BorderBrush" Value="{DynamicResource ButtonPressBorderBrush}" />
</Trigger>
<Trigger Property="IsDefaulted" Value="True">
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="{DynamicResource DefaultDisabledBrush}" />
<Setter TargetName="Border" Property="BorderBrush"
Value="{DynamicResource DisabledBorderBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<!--End Region Button-->

Office2007BlackStyle.xaml

<!--Region Colors-->

<Color x:Key="ButtonLight">
#EDEEF0
</Color>

<Color x:Key="ButtonDark">
#BBC0C6
</Color>

<Color x:Key="ButtonDisableLight">
#F3F6F8
</Color>

<Color x:Key="ButtonDisableDark">
#CBD5DF
</Color>

<Color x:Key="ButtonPressLight">
#F4BC81
</Color>

<Color x:Key="ButtonPressDark">
#EB7A05
</Color>

<Color x:Key="ButtonMouseOverLight">
#FBEDBD
</Color>

<Color x:Key="ButtonMouseOverDark">
#F4B100
</Color>

<Color x:Key="DefaultButtonBorderColor">
#898785
</Color>

<Color x:Key="TextBoxBorderColor">
#ABC1DE
</Color>

<Color x:Key="DisabledBorderColor">
#A1BDCF
</Color>

<Color x:Key="ButtonPressBorderColor">
#9B8259
</Color>

<Color x:Key="FontColor">
#464646
</Color>

<Color x:Key="BackgroundColor">
#535353
</Color>

<Color x:Key="GroupBoxColor">
#1E1E1E
</Color>

<!--End Region Colors-->

<CornerRadius x:Key="ButtonCornerRadius">
2
</CornerRadius>


<!--Region Brushes-->

<SolidColorBrush x:Key="DefaultButtonBorderBrush" Color="{DynamicResource DefaultButtonBorderColor}" />
<SolidColorBrush x:Key="TextBoxBorderBrush" Color="{DynamicResource TextBoxBorderColor}"/>
<SolidColorBrush x:Key="DisabledBorderBrush" Color="{DynamicResource DisabledBorderColor}" />
<SolidColorBrush x:Key="DefaultLabelBrush" Color="{DynamicResource ButtonLight}" />
<SolidColorBrush x:Key="ButtonPressBorderBrush" Color="{DynamicResource ButtonPressBorderColor}"/>
<SolidColorBrush x:Key="FontColorBrush" Color="{DynamicResource FontColor}"/>
<SolidColorBrush x:Key="DefaultBackgroundBrush" Color="{DynamicResource BackgroundColor}"/>
<SolidColorBrush x:Key="GroupBoxColorBrush" Color="{DynamicResource GroupBoxColor}"/>
<SolidColorBrush x:Key="TextBoxBackgroundBrush" Color="White"/>
<SolidColorBrush x:Key="TextBoxMouseOverBrush" Color="White"/>
<SolidColorBrush x:Key="TextBoxKeyboardFocusBrush" Color="White"/>

<LinearGradientBrush x:Key="DefaultButtonBrush" StartPoint="0,0" EndPoint="0,1.0">
<GradientStop Color="{DynamicResource ButtonLight}" Offset="0" />
<GradientStop Color="{DynamicResource ButtonDark}" Offset=".5" />
<GradientStop Color="{DynamicResource ButtonLight}" Offset="1" />
</LinearGradientBrush>

<LinearGradientBrush x:Key="DefaultDisabledBrush" StartPoint="0,0" EndPoint="0,1.0">
<GradientStop Color="{DynamicResource ButtonDisableLight}" Offset="0" />
<GradientStop Color="{DynamicResource ButtonDisableDark}" Offset=".5" />
<GradientStop Color="{DynamicResource ButtonDisableLight}" Offset="1" />
</LinearGradientBrush>

<LinearGradientBrush x:Key="ButtonPressBrush" StartPoint="0,0" EndPoint="0,1.0">
<GradientStop Color="{DynamicResource ButtonPressLight}" Offset="0" />
<GradientStop Color="{DynamicResource ButtonPressDark}" Offset=".5" />
<GradientStop Color="{DynamicResource ButtonPressLight}" Offset="1" />
</LinearGradientBrush>

<LinearGradientBrush x:Key="DefaultMouseOverBrush" StartPoint="0,0" EndPoint="0,1.0">
<GradientStop Color="{DynamicResource ButtonMouseOverLight}" Offset="0" />
<GradientStop Color="{DynamicResource ButtonMouseOverDark}" Offset=".5" />
<GradientStop Color="{DynamicResource ButtonMouseOverLight}" Offset="1" />
</LinearGradientBrush>

<!--End Region Brushes-->

AppHost.cs

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Threading;

namespace EmbeddedWPFTest
{
public static class AppHost
{
private static readonly object AppLock = Guid.NewGuid();
private static Application _application;
private static ResourceDictionary _currentTheme;
private static ResourceDictionary _controlDictionary;
private static ResourceDictionary _resourceDictionary;
private static Dictionary<string, ResourceDictionary> _themes;

public static Dispatcher Dispatcher { get; set; }

public static Application CurrentApplication
{
get
{
lock (AppLock)
{
if (_application == null)
{
_application = new Application();

LoadDictionaries();
InitializeApplication();

}
}

return _application;
}
}

private static void InitializeApplication()
{
Application.Current.Resources.MergedDictionaries.Add(_resourceDictionary);
Application.Current.Resources.MergedDictionaries.Add(_controlDictionary);
_currentTheme = Application.LoadComponent(
new Uri(@"/EmbeddedWPFTest;component/Resources/Office2007BlueStyle.xaml",
UriKind.Relative))
as ResourceDictionary;
Application.Current.Resources.MergedDictionaries.Add(_currentTheme);
}

public static void ChangeTheme()
{
Application.Current.Resources.MergedDictionaries.Remove(_currentTheme);
InitializeApplication();


_currentTheme = Application.LoadComponent(
new Uri(@"/EmbeddedWPFTest;component/Resources/Office2007BlackStyle.xaml",
UriKind.Relative))
as ResourceDictionary;
Application.Current.Resources.MergedDictionaries.Add(_currentTheme);


}

private static void LoadDictionaries()
{
_resourceDictionary =
Application.LoadComponent(new Uri(@"/EmbeddedWPFTest;component/Resources/ResourceDictionary.xaml",
UriKind.Relative)) as ResourceDictionary;
_controlDictionary =
Application.LoadComponent(new Uri(@"/EmbeddedWPFTest;component/Resources/UserControlResourceDictionary.xaml",
UriKind.Relative)) as ResourceDictionary;
_themes = new Dictionary<string, ResourceDictionary>
{
{
"Office2007BlueStyle",
Application.LoadComponent(
new Uri(@"/EmbeddedWPFTest;component/Resources/Office2007BlueStyle.xaml",
UriKind.Relative))
as ResourceDictionary
},
{
"Office2007BlackStyle",
Application.LoadComponent(
new Uri(@"/EmbeddedWPFTest;component/Resources/Office2007BlackStyle.xaml",
UriKind.Relative))
as ResourceDictionary
}
};
}
}
}

我的目标是,当托管 WinForms 应用程序更改其主题时,我可以连接到该事件,并让 AppHost 更改为相应的资源字典。为了简单起见,我省略了那部分代码。在我现在正在运行的测试中,它是由于在 View 中按下按钮而发生的。同样,如果 View 托管在 WPF 容器中,它工作正常,但托管在 WinForms 容器中,它不会刷新或重绘。

最佳答案

我尝试了所有可以在 Internet 上找到的解决方案。我能让它工作的唯一方法是创建一个新的 View 副本。这不是最优雅的解决方案,但我认为只要您为每个 View 保留相同的底层 View 模型实例,它就不是一个糟糕的解决方案。

现在,我正在使用 MVVMLight 努力更新此代码库。 MVVMLight 带有一个漂亮的信使实用程序,可以方便地进行模块之间的异步通信。我决定利用它在我的 AppHost 类和 WinForms 主机之间进行通信。

新建 AppHost.cs

public static class AppHost
{
private static readonly object AppLock = Guid.NewGuid();
private static Application _application;
private static ResourceDictionary _currentTheme;
private static ResourceDictionary _controlDictionary;
private static ResourceDictionary _resourceDictionary;
private static Dictionary<string, ResourceDictionary> _themes;
private static KryptonManager _kryptonManager;
private static IMessenger _messengerInstance;

/// <summary>
/// Gets or sets an instance of a <see cref="IMessenger" /> used to
/// broadcast messages to other objects. If null, this class will
/// attempt to broadcast using the Messenger's default instance.
/// </summary>
private static IMessenger MessengerInstance
{
get
{
return _messengerInstance ?? Messenger.Default;
}
set
{
_messengerInstance = value;
}
}

public static Application CurrentApplication
{
get
{
lock (AppLock)
{
if (_application == null)
{
_application = new Application();

LoadDictionaries();
InitializeApplication();
ChangeTheme(PaletteModeManager.Custom);

KryptonManager.GlobalPaletteChanged += KryptonManagerGlobalPaletteChanged;
_kryptonManager = new KryptonManager();
}
}

return _application;
}
}

private static void KryptonManagerGlobalPaletteChanged(object sender, EventArgs e)
{
ChangeTheme(_kryptonManager.GlobalPaletteMode);
}

private static void InitializeApplication()
{
Application.Current.Resources.MergedDictionaries.Add(_resourceDictionary);
Application.Current.Resources.MergedDictionaries.Add(_controlDictionary);
}

public static void ChangeTheme(PaletteModeManager manager)
{
Application.Current.Resources.MergedDictionaries.Remove(_currentTheme);

switch (manager)
{
case PaletteModeManager.Office2007Blue:
_currentTheme = _themes["Office2007BlueStyle"];
Application.Current.Resources.MergedDictionaries.Add(_currentTheme);
break;
case PaletteModeManager.Office2007Black:
_currentTheme = _themes["Office2007BlackStyle"];
Application.Current.Resources.MergedDictionaries.Add(_currentTheme);
break;
default:
_currentTheme = _themes["Office2007BlueStyle"];
Application.Current.Resources.MergedDictionaries.Add(_currentTheme);
break;
}

MessengerInstance.Send(new ThemeChangedMessage());
}

private static void LoadDictionaries()
{
_resourceDictionary =
Application.LoadComponent(new Uri(@"/ApplicationHost;component/Resources/ResourceDictionary.xaml",
UriKind.Relative)) as ResourceDictionary;
_controlDictionary =
Application.LoadComponent(new Uri(@"/ApplicationHost;component/Resources/UserControlResourceDictionary.xaml",
UriKind.Relative)) as ResourceDictionary;
_themes = new Dictionary<string, ResourceDictionary>
{
{
"Office2007BlueStyle",
Application.LoadComponent(
new Uri(@"/ApplicationHost;component/Resources/Office2007BlueStyle.xaml",
UriKind.Relative))
as ResourceDictionary
},
{
"Office2007BlackStyle",
Application.LoadComponent(
new Uri(@"/ApplicationHost;component/Resources/Office2007BlackStyle.xaml",
UriKind.Relative))
as ResourceDictionary
}
};
}
}

所以在这里,当 AppHost 收到来自 WinForms 主机(在本例中为 Krypton)的通知时,它会换出正确的颜色资源字典,然后使用 MVVMLight 的消息传递功能发送异步消息以通知监听器主题已更改.

BaseFormsWrapper.cs

public class BaseFormsWrapper : UserControl
{
public Panel PanelBasePanel;
private ElementHost _wpfHost;
private IMessenger _messengerInstance;

public BaseFormsWrapper()
{
InitializeComponent();
MessengerInstance.Register<ThemeChangedMessage>(this, HandleThemeChanged);
}

private void HandleThemeChanged(ThemeChangedMessage obj)
{
var instance = Activator.CreateInstance(_wpfHost.Child.GetType());
var oldView = _wpfHost.Child;
_wpfHost.Child = (UIElement) instance;

var view = oldView as ViewBase;
var newView = instance as ViewBase;

if ((view != null) && (newView != null))
{
newView.DataContext = view.DataContext;
}
}

/// <summary>
/// Gets or sets an instance of a <see cref="IMessenger" /> used to
/// broadcast messages to other objects. If null, this class will
/// attempt to broadcast using the Messenger's default instance.
/// </summary>
private IMessenger MessengerInstance
{
get
{
return _messengerInstance ?? Messenger.Default;
}
set
{
_messengerInstance = value;
}
}

public UIElement HostedControl
{
get { return _wpfHost.Child; }
set { _wpfHost.Child = value; }
}

private void InitializeComponent()
{
PanelBasePanel = new Panel();
_wpfHost = new ElementHost();
PanelBasePanel.SuspendLayout();
SuspendLayout();
//
// panelBasePanel
//
PanelBasePanel.AutoSizeMode = AutoSizeMode.GrowAndShrink;
PanelBasePanel.Controls.Add(_wpfHost);
PanelBasePanel.Dock = DockStyle.Fill;
PanelBasePanel.Location = new Point(0, 0);
PanelBasePanel.Margin = new Padding(0);
PanelBasePanel.Name = "PanelBasePanel";
PanelBasePanel.Size = new Size(1126, 388);
PanelBasePanel.TabIndex = 0;
//
// wpfHost
//
_wpfHost.BackColor = SystemColors.ControlLightLight;
_wpfHost.BackgroundImageLayout = ImageLayout.None;
_wpfHost.Dock = DockStyle.Fill;
_wpfHost.Location = new Point(0, 0);
_wpfHost.Name = "_wpfHost";
_wpfHost.Size = new Size(1126, 388);
_wpfHost.TabIndex = 0;
_wpfHost.Child = null;
//
// BaseFormsWrapper
//
AutoScaleDimensions = new SizeF(6F, 13F);
AutoSize = true;
Controls.Add(PanelBasePanel);
Name = "BaseFormsWrapper";
Size = new Size(1126, 388);
PanelBasePanel.ResumeLayout(false);
ResumeLayout(false);
}
}

在让 GC 处理旧 View 实例之前,我通过将其填充到新 View 实例中来保留其 DataContext( View 模型)。

我仍在处理我的概念验证工作项目,以确保所有这些在完成所有步骤后都能正常工作,但在我的初始测试中似乎很活泼且功能正常。

关于c# - 在 WinForms 中托管时管理 WPF 主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39704398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com