这是关于RichTextBoxes in a grid的问题的后续内容。我已经走得很远,但现在必须转换为MVVM。我的typeconverter没有被调用,所以问题可能出在我的数据绑定中。我使用两个数据网格来更快地测试设置。
View获取具有所有数据的ViewModel。
<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填充了我的自定义类的对象。我知道这有数据作为填充它的方法被调用。和我的转换器,它位于项目根命名空间
中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;
}
}
约束:
答案 0 :(得分:1)
问题在于你的绑定,你没有正确设置DataContext,没有加载数据,因此你的转换器没有被调用。
进行2项更改:
首先,将您的视图DataContext
设置为DifferenceViewModel
:
public DifferenceView(ViewModel.DifferenceViewModel differenceViewModel)
{
this.DataContext = differenceViewModel;
InitializeComponent();
}
然后,改变你的约束力:
而不是:
ItemsSource="{Binding Source=DifferenceViewModel, Path=DifferenceData, Converter={StaticResource DifferenceToTextConverter}}"
将其更改为:
ItemsSource="{Binding DifferenceData, Converter={StaticResource DifferenceToTextConverter}}"
这基本上意味着:
ItemsSource="{Binding Path=DifferenceData, Converter={StaticResource DifferenceToTextConverter}}"
由于您的DataContext是DifferenceViewModel,它将直接转到DifferenceData
属性。您现在可以在转换器中放置一个断点。