I have DataGrid
, which binds to DataTable
, because i don't know the amount of columns at compile time.
XAML
<Window.Resources>
<wpfApplication1:MainWindowViewModel x:Key="ViewModel" />
</Window.Resources>
<Grid DataContext="{StaticResource ViewModel}">
<DataGrid x:Name="MyDataGrid"
ItemsSource="{Binding Path=DataTable}" />
</Grid>
MainWindowViewModel.cs
class MainWindowViewModel : INotifyPropertyChanged
{
private DataTable dt;
public event PropertyChangedEventHandler PropertyChanged;
public MainWindowViewModel()
{
DataTable table = new DataTable();
table.Columns.Add("Foo", typeof(int));
table.Columns.Add("Bar", typeof(string));
table.Rows.Add(1, "first");
table.Rows.Add(2, null);
DataTable = table;
}
private void OnPropertyChanged(string s)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(s));
}
}
public DataTable DataTable
{
get { return dt; }
set
{
dt = value;
OnPropertyChanged("DataTable");
}
}
}
The result is:
There is nothing in the cell with null
value.
My question is: How can i change all the cells with null
value to '-' without changing the source DataTable
.
I can't use converter in binding because it will try to convert all the DataTable
, not the values.
I had no luck with DataGridCell
styles also because i don't know how to get the data value and change it.
Edit
My final solution is based on one of the answers. I create MyDataGrid
class and override OnAutoGeneratingColumn
method.
class MyDataGrid : DataGrid
{
protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
{
var textColumn = e.Column as DataGridTextColumn;
if (textColumn != null)
{
var binding = textColumn.Binding;
binding.TargetNullValue = "-";
}
base.OnAutoGeneratingColumn(e);
}
}