问题
I have to define a combobox through code behind:
var cmbLogin = new ComboBox()
{
Width = 200,
Height = m_dFontSize + 10,
FontSize = m_dFontSize,
Margin = new Thickness(20),
BorderBrush = new SolidColorBrush(m_ExeCfg.GetForeground()),
HorizontalContentAlignment = HorizontalAlignment.Center,
Background = Brushes.Transparent,<--------------HERE
Foreground = new SolidColorBrush(m_ExeCfg.GetForeground()),
Focusable = true,
};
so the background gets transparent in win7 but not in win10.
I have seen some solutions through xaml but could'nt apply them in code behind only. Thanx
回答1:
You can't simply set the Background property of the ComboBox to change its background on Windows 8 and 10. You will need to define a custom control template as suggested here: https://blog.magnusmontin.net/2014/04/30/changing-the-background-colour-of-a-combobox-in-wpf-on-windows-8/.
Once you have copied the default template into your XAML markup you could set the Background property of the "templateRoot" Border element in the ToggleButton style to {TemplateBinding Background}
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border x:Name="templateRoot" BorderBrush="{StaticResource ComboBox.Static.Border}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
...
You will then have to apply the custom style to the ComboBox that you are creating programmatically:
var cmbLogin = new ComboBox()
{
Width = 200,
Height = m_dFontSize + 10,
FontSize = m_dFontSize,
Margin = new Thickness(20),
BorderBrush = new SolidColorBrush(m_ExeCfg.GetForeground()),
HorizontalContentAlignment = HorizontalAlignment.Center,
Background = Brushes.Transparent,
Foreground = new SolidColorBrush(m_ExeCfg.GetForeground()),
Focusable = true,
Style = Resources["ComboBoxStyle1"] as Style
};
If you really, really want to this without using any XAML markup at all you will have to wait until the ComboBox has been loaded and then find the Border element in the visual tree and set its Background property:
var cmbLogin = new ComboBox()
{
Width = 200,
Height = m_dFontSize + 10,
FontSize = m_dFontSize,
Margin = new Thickness(20),
BorderBrush = new SolidColorBrush(m_ExeCfg.GetForeground()),
HorizontalContentAlignment = HorizontalAlignment.Center,
Foreground = new SolidColorBrush(m_ExeCfg.GetForeground()),
Focusable = true,
};
cmbLogin.Loaded += (ss, ee) =>
{
var toggleButton = cmb.Template.FindName("toggleButton", cmbLogin) as System.Windows.Controls.Primitives.ToggleButton;
if(toggleButton != null)
{
Border border = toggleButton.Template.FindName("templateRoot", toggleButton) as Border;
if (border != null)
border.Background = Brushes.Transparent;
}
};
来源:https://stackoverflow.com/questions/41761792/wpf-combobox-transparent-background-not-working-with-windows-10