Reputation: 5281
In WPF, how can I prefix all cells in an editable datagrid column with a dollar sign ($
), and still bind to a CLR object property of type decimal?
The MSDN documentation tends to point towards styles as ways to customize the visual appearance of elements in a datagrid (see here). However, I don't want to set a property. I want to prefix the data with a dollar sign.
I've tried using data templates. Here's an excerpt from my XAML, showing the data template:
...
<Window.Resources>
<DataTemplate DataType="{x:Type Binding}" x:Key="myDataTemplate">
<TextBlock>
<Run>$</Run>
<TextBox Text="{Binding}"></TextBox>
</TextBlock>
</DataTemplate>
</Window.Resources>
...
However, the only place I can find to include this in the datagrid is in the HeaderTemplate
property of DataGridTextColumn
, as in this excerpt further down in the same XAML. This displays $
followed by a textbox in the header only. I would like this to happen not in the header, but in all other cells in that row.
...
<DataGrid.Columns>
<DataGridTextColumn Header="Header1"
Binding="{Binding Path=decimalProperty}"
HeaderTemplate="{StaticResource myDataTemplate}">
</DataGridTextColumn>
</DataGrid.Columns>
...
Of course there is code-behind, but the skeletal outline here should describe what I'm trying to do.
Simply changing the property to type string in the code, and prefixing with a dollar sign, is not an option.
Upvotes: 0
Views: 881
Reputation: 23831
I have just seen your edit, just use formatting on the text binding._
<TextBlock Text="{Binding YourText, StringFormat={}{0:C}}"/>
I hope this helps.
Upvotes: 1
Reputation: 4606
Here is another option:
XAML:
<DataGrid AutoGeneratingColumn="OnAutoGeneratingColumn"/>
Code:
private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof(decimal))
((DataGridBoundColumn)e.Column).Binding.StringFormat = "c";
}
Upvotes: 0
Reputation: 5366
You can use DataGridTemplateColumn. Refer below code.
<DataGridTemplateColumn Header="Header1" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock>
<Run>$</Run>
<TextBox Text="{Binding decimalProperty}"/>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Upvotes: 1