重新设计WinForm应用程序中托管的WPF控件的样式



我正在尝试将黑暗主题支持添加到我的爱好应用程序中。应用程序是WinForms,我不想在WPF中重写UI。因此,我尝试在我的应用程序中添加几个WPF控件,主要是因为它们允许对滚动条进行主题化。

我遵循本教程进行主机控制:https://www.codeproject.com/Articles/739902/How-to-Easily-Host-WPF-Control-inside-Windows-Form

到目前为止一切正常,只是我不能动态更改WinForms中托管的WPF控件的背景颜色。我尝试了很多方法,引发属性更改、调用SetValue等,但我控制Background/Foreground的唯一方法是直接在XAML中设置它们,这不是我想要的,因为我希望能够选择性地更改颜色。

以下是我认为最接近我想要的:

System.Windows.Style style = new System.Windows.Style();
style.TargetType = typeof(WpfControls.ListViewControl);
style.Setters.Add(new System.Windows.Setter(WpfControls.ListViewControl.BackgroundProperty, System.Windows.Media.Brushes.Pink));
style.Setters.Add(new System.Windows.Setter(WpfControls.ListViewControl.ForegroundProperty, System.Windows.Media.Brushes.Red));
this.listViewControl.Style = style;

颜色不变。代码在这里:https://github.com/TheIronWolfModding/WpfControlsWinFormsHost/blob/master/WindowsFormsHost_Test/Form1.cs

实际上您的代码工作正常。您的ListViewControl具有误导性,因为它是包含ListView控件的UserControl。您正确地将样式应用于UserControl,但ListView使其模糊,因此您看不到更改。如果需要证明,可以使包含的ListViewBackground透明。

要修复它,您可以在ListViewControl中更改XAML,以便ListView从父容器获取其前景和背景。

<ListView x:Name="listView" ItemsSource="{Binding ListEntries}" ScrollViewer.VerticalScrollBarVisibility="Visible"
Background="{Binding Parent.Background, RelativeSource={RelativeSource Self}}"
Foreground="{Binding Parent.Foreground, RelativeSource={RelativeSource Self}}">
</ListView>

或由于您的意图可能也是修改样式中的许多其他属性,因此不必为每个属性不断添加类似的绑定,因此您可以获得对所包含的ListView控件的引用,并直接设置其样式。相反,不要使用XAML,而是将其添加到Form1.cs代码中:

System.Windows.Style style = new System.Windows.Style();
style.TargetType = typeof(System.Windows.Controls.ListView);
style.Setters.Add(new System.Windows.Setter(WpfControls.ListViewControl.BackgroundProperty, System.Windows.Media.Brushes.Pink));
style.Setters.Add(new System.Windows.Setter(WpfControls.ListViewControl.ForegroundProperty, System.Windows.Media.Brushes.Red));
//this.listViewControl.Style = style;
var listview = listViewControl.FindName ("listView") as System.Windows.Controls.ListView;
if (listview != null) {
listview.Style = style;
}

注意:一定要更改TargetType,它需要与ListView控件匹配才能工作。

最新更新