mercredi 6 mai 2015

WPF, datagrid cell prefixing

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.

Aucun commentaire:

Enregistrer un commentaire