I am working with a Wpf application. I have created a custom style for wpf DataGrid
(provided in Wpf Toolkit). It all works fine except that I am unable to apply a Style
on the TextBox
that comes on double clicking the cell(editable mode) in DataGridTextColumn
. It display as default style and that doesn't match with my style and looks odd. I have applied a style on the ComboBox
in DataGridComboBoxColumn
and the CheckBox
and all other controls, but this one is not working. Any help plz!!!
I have a control library and every control is overridden here for customization (additional functionality) and restyling. These controls are used through out the application. I have to apply this style on the control in control library. So that I can get it reflected in my whole application.
Not perfect, but works...
<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}"/>
This can also be achieved with the PreparingCellForEdit
event of the DataGrid
, if you don't want to override the system EditingElementStyle
, or if use AutoGenerateColumns
, or when you have multiple columns and can't afford to set them individually.
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;
}
If you want to apply app resources:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.