Reputation: 105
Some days I really regret ever going down the route of using WPF for an application...
I am trying to use DataGridComboBoxColumn
and all I want to do is apply padding to the text in the cell when it is not being edited but it seems they made that an impossible task
<Window.Resources>
<CollectionViewSource x:Key="Statuses" Source="{Binding Path=Statuses}" />
</Window.Resources>
<DataGridComboBoxColumn Header="Status"
Width="100"
ItemsSource="{Binding Source={StaticResource Statuses}}"
DisplayMemberPath="Description"
SelectedValuePath="Index"
SelectedValueBinding="{Binding Path=Status}">
<DataGridComboBoxColumn.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Padding" Value="4,2" />
</Style>
</DataGridComboBoxColumn.CellStyle>
</DataGridComboBoxColumn>
I tried setting ElementStyle
and overriding the Template
but this just causes some weird validation error and after a quick internet search it seems this is a bad option to take.
I then resorted to using a DataGridTemplateColumn but this leaves me trying to convert my Binding Value back into the same text as the ComboBox DisplayMemberPath
and my attempt at using a ValueConverter
failed as it never passed a value from my CollectionViewSource "Statuses".
Now I have run out of patience and will just have to accept that I can't style these cells, unless someone out there has a quick and reliable fix for this?
Edit: I have created a GitHub Repository with an example of what I am trying to do, there is also a branch named 'value-converter' with my failed attempt at implementing IValueConverter
and using DataGridTemplateColumn
.
Upvotes: 2
Views: 457
Reputation: 534
Have you tried setting Margin for the ElementStyle?
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="Margin" Value="5,0,5,0"/>
</Style>
</DataGridComboBoxColumn.ElementStyle>
Upvotes: 0
Reputation: 169350
The easiest way to fix this is probably to define a custom ComboBoxColumn
and set the Margin
property of the element generated in the GenerateElement
method:
public class CustomComboBoxColumn : System.Windows.Controls.DataGridComboBoxColumn
{
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
FrameworkElement fe = base.GenerateElement(cell, dataItem);
if (fe is Control control)
control.Margin = new Thickness(4, 2, 4, 2);
return fe;
}
}
Usage:
<local:CustomComboBoxColumn Header="Status"
Width="100"
ItemsSource="{Binding Source={StaticResource Statuses}}"
DisplayMemberPath="Description"
SelectedValuePath="Index"
SelectedValueBinding="{Binding Path=Status}" />
Upvotes: 1