【问题标题】:How can I change the border color of a combobox in WPF by code (c#)?如何通过代码(c#)更改 WPF 中组合框的边框颜色?
【发布时间】:2020-05-05 14:44:10
【问题描述】:
有人知道怎么做吗?如果 ComboBox 没有被选中,我需要标记它。
此方法无效:
cBoxBasics.BorderBrush = System.Windows.Media.Brushes.Red;
提前致谢。
【问题讨论】:
标签:
c#
wpf
combobox
border
【解决方案1】:
一个快速而肮脏的解决方案是用边框元素包围组合框并在 xaml 中设置边框元素颜色...
<Border x:Name="MyBorder" BorderBrush="Red" BorderThickness="2">
<ComboBox x:Name="cBoxBasics" />
</Border>
...或在后面的代码中
MyBorder.BorderBrush = System.Windows.Media.Brushes.Red;
正如其他人在 cmets 中所述,您可以实施验证功能。虽然它们的实现和学习可能有点复杂。
【解决方案2】:
如果您暂时为您的 ComboBox 使用 create a new resource 并使用它,您会看到它包含一个名为 templateRoot 的边框元素,您需要设置它的颜色。由于您需要更改的是 ToggleButton 的根子控件,并且它的父 ComboBox 也包含其自己的 templateRoot 命名控件,因此这会稍微复杂一些。因此,要更改 ToggleButton 边框的颜色,您需要首先在 ComboBox 中找到它,然后找到它的 templateRoot Border 元素并在那里设置颜色。您还需要确保在控件模板化后执行此操作,否则将不会有任何更改,因此请在 cBoxBasics 的 Loaded 处理程序中执行此操作:
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
this.cBoxBasics.Loaded += (s, e) =>
{
var toggleButton = this.cBoxBasics.Template.FindName("toggleButton", this.cBoxBasics) as ToggleButton;
var border = toggleButton.Template.FindName("templateRoot", toggleButton) as Border;
border.BorderBrush = Brushes.Red;
};
}