我知道您可以右鍵單擊,編輯模板> 編輯副本,粘貼整個 ComboBox 模板然后更改幾行,但是真的沒有辦法只用幾行代碼來更改背景嗎?
我可以用這段代碼來實作它,但這消除了基本上使它無用的下拉箭頭/選單。
<Style TargetType="{x:Type ComboBox}">
<Setter Property="Background" Value="Red" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ComboBox}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter></ContentPresenter>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
uj5u.com熱心網友回復:
恐怕您不能僅“覆寫” a 的一部分,ControlTemplate并且鑒于定義默認值的方式ControlTemplate,ComboBox您不能簡單地設定或屬性或使用觸發器創建派生樣式來更改其背景顏色。這在這里詳細解釋。
您可以做的是在運行時以編程方式更改加載的模板元素的背景:
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
ComboBox comboBox = (ComboBox)sender;
ToggleButton toggleButton = comboBox.Template.FindName("toggleButton", comboBox) as ToggleButton;
if (toggleButton != null)
{
Border border = toggleButton.Template.FindName("templateRoot", toggleButton) as Border;
if (border != null)
border.Background = Brushes.Yellow;
}
}
XAML:
<ComboBox Loaded="ComboBox_Loaded">
<ComboBoxItem Background="Yellow">1</ComboBoxItem>
<ComboBoxItem Background="Yellow">2</ComboBoxItem>
<ComboBoxItem Background="Yellow">3</ComboBoxItem>
</ComboBox>
另一種選擇是將整個模板復制到您的 XAML 標記中并根據您的要求對其進行編輯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424237.html
