3

我正在使用 Wpf 应用程序。我为 wpf 创建了一个自定义样式DataGrid(在 Wpf Toolkit 中提供)。一切正常,除了我无法StyleTextBox双击单元格(可编辑模式)时应用DataGridTextColumn. 它显示为默认样式,与我的样式不匹配,看起来很奇怪。我已经在ComboBoxinDataGridComboBoxColumn和 theCheckBox以及所有其他控件上应用了一种样式,但是这个样式不起作用。任何帮助请!

编辑:

我有一个控件库,每个控件都在这里被覆盖以进行自定义(附加功能)和重新设置样式。这些控件在整个应用程序中使用。我必须在控件库中的控件上应用这种样式。这样我就可以将它反映在我的整个应用程序中。

4

2 回答 2

5

不完美,但工作...

<Style x:Key="DataGridTextBoxStyle"
    TargetType="TextBox">
    <Setter
        Property="SelectionBrush"
        Value="#FFF8D172" />
    <Setter
        Property="Padding"
        Value="0" />
    <Setter
        Property="VerticalContentAlignment"
        Value="Center" />
    <Setter
        Property="FontSize"
        Value="9pt" />
    <Setter
        Property="SelectionOpacity"
        Value="0.6" />
</Style>

<DataGridTextColumn
   x:Name="TextColumn"
   Header="Header"
   EditingElementStyle="{StaticResource ResourceKey=DataGridTextBoxStyle}"/>
于 2011-03-21T23:01:19.507 回答
0

这也可以通过 的PreparingCellForEdit事件来实现DataGrid,如果您不想覆盖系统EditingElementStyle,或者如果使用AutoGenerateColumns,或者当您有多个列并且无法单独设置它们时。

private void DataGrid_PreparingCellForEdit(object sender, 
  DataGridPreparingCellForEditEventArgs e)
{
  if (!(e.Column is DataGridTextColumn && e.EditingElement is TextBox textBox))
    return;

  var style = new Style(typeof(TextBox), textBox.Style);        
  style.Setters.Add(new Setter { Property = ForegroundProperty, Value = Brushes.Red });
  textBox.Style = style;      
}

如果要应用应用资源:

private void DataGrid_PreparingCellForEdit(object sender, 
  DataGridPreparingCellForEditEventArgs e)
{
  if (!(e.Column is DataGridTextColumn && e.EditingElement is TextBox textBox))
    return;

  var tbType = typeof(TextBox);
  var resourcesStyle = Application
    .Current
    .Resources
    .Cast<DictionaryEntry>()
    .Where(de => de.Value is Style && de.Key is Type styleType && styleType == tbType)
    .Select(de => (Style)de.Value)
    .FirstOrDefault();

  var style = new Style(typeof(TextBox), resourcesStyle);
  foreach (var setter in textBox.Style.Setters)
    style.Setters.Add(setter);

  textBox.Style = style;
}
于 2019-12-10T02:50:28.880 回答