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

重新设置WinForm应用程序中托管的WPF控件的样式,wpf,winforms,elementhost,Wpf,Winforms,Elementhost,我正在尝试将黑色主题支持添加到我的嗜好应用程序中。应用程序是WinForms,我不想在WPF中重写UI。因此,我尝试在我的应用程序中添加几个WPF控件,主要是因为它们允许滚动条主题化 我将按照本教程介绍主机控制: 到目前为止,一切都正常,只是我不能动态更改WinForms中承载的WPF控件的背景色。我尝试了很多方法,提高属性更改,调用SetValue等,但我控制背景/前景的唯一方法是直接在XAML中设置它们,这不是我想要的,因为我希望能够选择性地更改颜色 以下是我想象中最接近我想要的: Syst

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

我将按照本教程介绍主机控制:

到目前为止,一切都正常,只是我不能动态更改WinForms中承载的WPF控件的背景色。我尝试了很多方法,提高属性更改,调用SetValue等,但我控制背景/前景的唯一方法是直接在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;

颜色不变。代码在这里:

实际上,您的代码工作正常。您的
列表视图控件
具有误导性,因为它是一个
用户控件
,包含
列表视图
控件。您正在正确地将样式应用于
用户控件
,但
列表视图
将其遮挡,因此您无法看到更改。如果需要校样,可以将包含的
列表视图
背景
透明化

要修复它,您可以在
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>
注意:请确保更改了
TargetType
,它需要与
ListView
控件匹配才能工作

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;
}