Setting a design-time data context in XAML so that Intellisense works

Intellisense is a great help, when it works. Unfortunately, it only works when VS knows the context in which you are typing. This is generally not a problem in C#, but can be in XAML, where you often create isolated snippets.

For example, we have a GridView that displays systems. We show a tooltip when the user hovers over a row.

Whilst it would be nice to be able to set the tooltip directly in the GridView code, it can’t be done that way. Instead, you have to set up the tooltip as a resource and reference it in the grid using the RowLoaded event. This is a pain. First you need to hook up to the event…

<telerik:RadGridView
  RowLoaded"VRTSystemsGrid_RowLoaded"
  ... other stuff here

…and then in the code behind…

private void SetToolTip(GridViewRow row)
{
  ToolTip toolTip = new ToolTip
  {
    Content = row.DataContext,
    ContentTemplate = (DataTemplate)LayoutRoot.Resources["VrtSystemToolTip"]
  };
  ToolTipService.SetToolTip(row, toolTip);
}

The tooltip itself is set in a resource in the XAML…

<Grid.Resources>
  <DataTemplate x:Key="VrtSystemToolTip">
    <Grid>
      <TextBlock Text="{Binding ProductConfigurationDescription}"
                 Foreground="Blue" />
    </Grid>
  </DataTemplate>
</Grid.Resources>

This works, but as Visual Studio doesn’t know the context of the tooltip, it doesn’t know what to offer when you set the binding. I had to type ProductConfigurationDescription manually (well, copy and paste actually), and ignore the fact that Visual Studio underlines the binding, saying that it cannot resolve the property.

Thankfully, we can tell the XAML designer what context it should use, which will remove the underline, and give us Intellisense again. All we need to do is add a namespace entry in the header to specify the type for the data context. In this case, the data context for the tooltip is an entity in our Entities project. Thus, we need the following line in the opening tag of our XAML…

mc:Ignorable="d"
xmlns:entities="clr-namespace:MyEntities;assembly=MyEntities"

You may already have the first line, as it’s often used for other things, such as setting the design time size for a user control.

Now, we can modify the XAML for the tooltip to set the data context…

<Grid.Resources>
  <DataTemplate x:Key="VrtSystemToolTip">
    <Grid d:DataContext="{d:DesignInstance entities:Widget}">
      <TextBlock Text="{Binding ProductConfigurationDescription}"
                 Foreground="Blue" />
    </Grid>
  </DataTemplate>
</Grid.Resources>

Now all is well again and we have Intellisense.

If you use Resharper, then you can have it insert the basic code for you…

R# offering to add the basic code

Be First to Comment

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.