这也可以通过 的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;
}