【问题标题】:Restyle WPF Control hosted in a WinForm app重新设置 WinForm 应用程序中托管的 WPF 控件的样式
【发布时间】:2018-07-26 17:46:11
【问题描述】:

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

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

到目前为止一切正常,除了我无法动态更改托管在 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;

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

【问题讨论】:

    标签: wpf winforms elementhost


    【解决方案1】:

    实际上您的代码运行正常。您的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 控件才能工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多