如何使用代码更改ComboBox的边框颜色?

时间:2012-06-06 05:36:51

标签: wpf combobox border

我有一个ComboBox,我想将边框的颜色更改为红色,以将其标记为必填字段。我通过我的代码动态生成这个ComboBox列。为了更改边框颜色,我应该设置哪些属性?

  DataGridTemplateColumn dataGridComboBoxTemplateColumnObj = new DataGridTemplateColumn();
  dataGridComboBoxTemplateColumnObj.Header = column.Header;
  FrameworkElementFactory comboBoxFactory = new FrameworkElementFactory(typeof(ComboBox));
  Binding bindingItemSourceObj = new Binding(column.ItemsSourcePropertyName);
  comboBoxFactory.SetValue(ComboBox.HorizontalAlignmentProperty, HorizontalAlignment.Stretch);
  comboBoxFactory.SetValue(ComboBox.ItemsSourceProperty, bindingItemSourceObj);              
  comboBoxFactory.SetValue(ComboBox.SelectedValuePathProperty, column.ValuePropertyName);

  Binding selectedValueBindingObj = new Binding(column.PropertyName);
  selectedValueBindingObj.Mode = BindingMode.TwoWay;
  selectedValueBindingObj.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
  comboBoxFactory.SetValue(ComboBox.SelectedValueProperty, selectedValueBindingObj);
  dataGridComboBoxTemplateColumnObj.CellTemplate = new DataTemplate();
  dataGridComboBoxTemplateColumnObj.CellTemplate.VisualTree = comboBoxFactory;
  dataGridColumnObj = dataGridComboBoxTemplateColumnObj;

1 个答案:

答案 0 :(得分:2)

如果您有ComboBox

<ComboBox x:Name="MyComboBox"/>

您只需设置Border.BorderBrushProperty

的值即可
MyComboBox.SetValue(Border.BorderBrushProperty, Brushes.Red);

通过这种方式,您可以准确地将ComboBox的边框颜色更改为红色。

修改: 我为您的特定FrameworkElementFactory添加了此示例:

FrameworkElementFactory comboBoxFactory = new FrameworkElementFactory(typeof(ComboBox));
comboBoxFactory.SetValue(Border.BorderBrushProperty, Brushes.Red);

ControlTemplate ct = new ControlTemplate(typeof(ComboBox));
ct.VisualTree = comboBoxFactory;
MyComboBox.Template = ct;