Reputation: 2715
I have a wpf datagrid,
Here's my datagrid
<dg:DataGrid x:Name="dataGrid" AutoGenerateColumns="false"
ColumnHeaderStyle="{StaticResource columnHeaderStyle}"
AlternationCount="2" RowBackground="Beige"
RowStyle="{StaticResource rowStyle}"
AlternatingRowBackground="LightBlue"
HeadersVisibility="All"
HorizontalGridLinesBrush="#DDDDDD"
VerticalGridLinesBrush="#DDDDDD" Grid.ColumnSpan="2" Margin="0,0,0,26" IsReadOnly="True" ColumnHeaderHeight="30">
<dg:DataGrid.Columns>
<dg:DataGridTextColumn Header=" Task Id" Binding="{Binding Path=TaskId}" Width="60" />
<dg:DataGridTextColumn Header="Order Description" Binding="{Binding Path=OrderDescription}" Width="120"/>
<dg:DataGridTextColumn Header="Final Client Name" Binding="{Binding Path=ClientName}" Width="110"/>
<dg:DataGridTextColumn Header="Order Date" Binding="{Binding Path=OrderDate}" Width="80"/>
<dg:DataGridTextColumn Header="Task Description" Binding="{Binding Path=TaskDescription}" Width="130"/>
<dg:DataGridTextColumn Header="Group Name Short" Binding="{Binding Path=GroupNameShort}" Width="116"/>
<dg:DataGridTemplateColumn MinWidth="100" Header=" Actions">
<dg:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="DetailButton_Click">Close</Button>
</DataTemplate>
</dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
</dg:DataGrid.Columns>
</dg:DataGrid>
In aspx to change text we use onrowdatabound for example, here in wpf how can I change the field Order Description and Order Date. I have two functions to change the text, that are convertDatetimeToDate(string datetime) e htmltotext(string text).
Upvotes: 0
Views: 1400
Reputation: 59129
You can use a value converter on the binding. Create a class that implements IValueConverter, and set an instance of that class as the Converter property of the binding.
public class DateTimeToDateConverter
: IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
// Call convertDatetimeToDate here and return the result
return value;
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
In your XAML, create an instance of the converter. You may need to add a namespace reference:
<Window.Resources xmlns:local="clr-namespace:YourNamespace">
<local:DateTimeToDateConverter x:Key="myConverter"/>
</Window.Resources>
And use it in the binding:
<dg:DataGridTextColumn
Header="Order Date"
Binding="{Binding Path=OrderDate, Converter={StaticResource myConverter}}"
Width="80"/>
In 3.5 SP1 or later, you can also use the StringFormat property on the binding to do simple formatting. This should format the datetime as a plain date by doing the equivalent of string.Format("{0:d}", OrderDate)
:
<dg:DataGridTextColumn
Header="Order Date"
Binding="{Binding Path=OrderDate, StringFormat='{}{0:d}'}"
Width="80"/>
Upvotes: 2