Can a DataTemplate bind to a nested class?

Can a DataTemplate in XAML be associated with a nested class?

I am working on an MVVM application and I am facing a data pattern problem. I have a view model that provides a collection of other view models for managing items. These elements are part of the hierarchy, defined as nested classes in the appearance model. So far, I have not been able to create a mapping in XAML to reference an internal nested class.

Here is the class hierarchy (simplified for brevity):

public class MainViewModel { public class A { } public class B : A { } public class C : A { } public ObservableCollection<A> Items { get; set; } } 

In XAML, I am trying to map a DataTemplate to types B and C, but I cannot fully qualify the name of the nested class.

 <ItemsControl ItemsSource="{Binding Path=Items}"> <ItemsControl.Resources> <DataTemplate DataType="{x:Type ns:BracingViewModel.B}"> <Grid> .... </Grid> </DataTemplate> <DataTemplate DataType="{x:Type ns:BracingViewModel.C}"> <Grid> .... </Grid> </DataTemplate> </ItemsControl.Resources> </ItemsControl> 

Problem: references to nested classes appear as a build error in XAML. I get the following:

 Error 5 Cannot find the type 'ns:B'. Note that type names are case sensitive. Line... Error 5 Cannot find the type 'ns:C'. Note that type names are case sensitive. Line... 

If I move the hierarchy of classes A, B, C outside the MainViewModel class (i.e. to the namespace level), this works fine.

As a general habit, I try to ensure that classes related to the view model, defined as nested classes within it, can lead to this problem.

So my question is: is it possible to associate a DataTemplate with a nested class? If so, how is this done in the XAML part?

Thanks in advance ... Joe

+4
source share
1 answer

This works for me:

  <ItemsControl ItemsSource="{Binding Path=Items}"> <ItemsControl.Resources> <DataTemplate DataType="{x:Type ns:MainViewModel+B}"> <Grid Background="Blue" Width="30" Height="30"> </Grid> </DataTemplate> <DataTemplate DataType="{x:Type ns:MainViewModel+C}"> <Grid Background="Chartreuse" Width="30" Height="30"> </Grid> </DataTemplate> </ItemsControl.Resources> </ItemsControl> 

In other words, just change . to + in x:Type markup extension

credit: this flow

+17
source

Source: https://habr.com/ru/post/1438730/


All Articles