DataContext design time in DataTemplate?

When I put the DataTemplate in the <Page.Resources> section, it inherits the DataContext Page when editing the bindings inside the constructor. However, at run time, the DataTemplate used by an element within the Page that has its own DataContext . I want the designer to display the internal DataContext , and instead bind.

Is there a tag like d:DataContext for DataTemplates ? Installing DataType does nothing.

+4
source share
2 answers

I found that you can simply set d:DataContext on the root element inside the DataTemplate .

 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" <ListBox ItemsSource="{Binding People}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel d:DataContext="{d:DesignInstance Type=local:Person}"> <TextBlock Text="{Binding Name}" /> <TextBlock Text="{Binding Age}" /> <TextBlock Text="{Binding Height}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> 

+4
source

I understand that this is super old, but in order to make SO better. DataTemplates have a "DataContext" through the DataType tag.

 <DataTemplate DataType="{x:Type local:Person}"> <StackPanel> <TextBlock Text="{Binding Name}" /> <TextBlock Text="{Binding Age}" /> <TextBlock Text="{Binding Height}" /> </StackPanel> </DataTemplate> 
+2
source

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


All Articles