This is a followup on a question on RichTextBoxes in a grid. I’ve gotten pretty far but it must be converted to MVVM now. My typeconverter is not getting called so the problem is probably in my databinding. I use two datagrids to test setups quicker.
View gets a ViewModel that has the all the data.
<Window.Resources>
<local:DifferenceToTextConverter x:Key="DifferenceToTextConverter" />
<DataTemplate x:Key="cellTemplate" DataType="{x:Type Label}">
<Label Content="{Binding Converter={StaticResource ResourceKey=DifferenceToTextConverter}}" >
</Label>
</DataTemplate>
</Window.Resources>
<DataGrid Name="TestGrid"
ItemsSource="{Binding Source=DifferenceViewModel, Path=DifferenceData, Converter={StaticResource DifferenceToTextConverter}}"
HeadersVisibility="Column"
ItemTemplate="{StaticResource cellTemplate}" >
</DataGrid>
</DataGrid>
<DataGrid Name="OhterGrid" DataContext="{Binding ElementName=DifferenceViewModel, Path=DifferenceData}" HeadersVisibility="Column" >
<DataGrid.ItemTemplate>
<DataTemplate DataType="{x:Type Label}">
<Label Content="{Binding Converter={StaticResource ResourceKey=DifferenceToTextConverter}}" >
</Label>
</DataTemplate>
</DataGrid.ItemTemplate>
</DataGrid>
public DifferenceView(ViewModel.DifferenceViewModel differenceViewModel)
{
InitializeComponent();
this.DifferenceViewModel = differenceViewModel;
}
ViewModel, DataTable filled with objects of my custom class. I know this has data as the method to fill it get’s called. And my converter, which sits in the project root namespace
namespace ViewModel
{
public class DifferenceViewModel
{
private DataTable differenceData;
/// <summary>
/// Differences between properties.
/// </summary>
public DataTable DifferenceData
{
get
{
return this.differenceData;
}
private set
{
this.differenceData = value;
}
}
}
}
class DifferenceToTextConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type sourceType, object parameter, System.Globalization.CultureInfo culture)
{
TextBlock cell = new TextBlock();
// Convert custom data to text representation.
return cell;
}
}
Constraints:
- Use MVVM
- Style in xaml when possible.
- Text with style applied to individual letters.
- Unknown number of columns and rows.
- Custom typeconverter needs to construct the entire cell text.
The problem is your binding, you’re not setting the DataContext correctly, no data is loaded and therefore your converter isn’t being called.
Make 2 changes:
First, set your view’s
DataContextto theDifferenceViewModel:Then, change your binding:
Instead of this:
Change it to this:
Which basically means:
Since your DataContext is the DifferenceViewModel, it’ll directly go to the
DifferenceDataproperty. You can now put a breakpoint in your converter.