Home » WPF

How to databind the DataContext of a ContentPresenter's Content?

I have a ContainerWindow that has a ContentPresenter inside of it, defined using XAML. I have added a dependency proparty named ChildControl inside ContainerWindow so it can be databound to the ContentPresenter.Content.

Then I have the class ContainerWindowViewModel that contains a property named ChildControlViewModel,  and I would like to databind that property to the ContentPresenter.Content's DataContext. Is it possible to express this in XAML or does it have to be done in the code behind?





<UserControl x:Class="MyNamespace.ContainerWindow">
    <ContentPresenter Content="{Binding RelativeSource={RelativeSource Self}, Path=ChildControl}" />




class ContainerWindowViewModel
    public object ChildControlViewModel
        get { [...] }
        set { [...] }




2 Answers Found


Answer 1

Hi Sylvain,

There is a mistake in your code,
  <ContentPresenter Content="{Binding RelativeSource={RelativeSource Self}, Path=ChildControl}" />
the "RelativeSource Self" references to the ContentPresenter self; but as you said, the ContentPresenter does not have the property  ChildControl. So the correct is 
  <ContentPresenter Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type l:ContainerWindow}}, Path=ChildControl}" />

And you can create a ContainerWindowViewModel instance in xaml  by resources, then bind ContentPresenter.DataContext to this static resource.

code snippet:

<UserControl x:Class="MyNamespace.ContainerWindow"
  Height="300" Width="300"
  <l:ContainerWindowViewModel x:Key="containerWindowViewModel"/>
 <ContentPresenter DataContext="{Binding Source={StaticResource containerWindowViewModel}, Path=ChildControlViewModel}"
          Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type l:ContainerWindow}}, Path=ChildControl}" />

If you have any problem, please feel free to let me know.


Bob Bao


Answer 2

Is there a way to make this work with a data context that would not be created as a static resource by XAML?

When I set  a Data context binding in my ContentPresenter, the binding appears to be ignored.

When I do the following:

<ContentPresenterDataContext="{Binding ChildControlViewModel}"Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type l:ContainerWindow}}, Path=ChildControl}"/>

I get binding errors for my child control as it looks for the properties in the ContainerWindowViewModel instead of the ChildControlViewModel. If I remove the binding:

<ContentPresenterContent="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type l:ContainerWindow}}, Path=ChildControl}"/>

I get the same result. So it is as if binding this way would do nothing in my code.



Hey All,


We have a ContentPresenter who's Content property is bound to a Converter and set dynamically.

We're noticing that at runtime, the UserControl of which is the Content property of the previously mentioned ContentPresenter, has its Parent property set to null.


The parent is obviously the ContentPresenter, but the Parent property is null in this case. This seems to be occurring when the Content property is bound in XAML with a Converter to find the View to bind to.


Hi all,

I've tried to bind the 'Content' property of a ContentPresenter control so that I can swap the visible content inside it (it's the toolkits TransitionalContentPresenter, but I've also tried this with the regular ContentPresenter so I don't think it's a bug).

I want to make different content appear in this panel depending on the users actions on screen.

I've created a DependencyProperty to bind to, and set the binding of the Content to point to the property. I've also set the DataContext of the UserControl to itself, so that it can pick up the property. During debug I can see that the property gets set, but the app throws a 'Value does not fall within expected range' error

The object that I want to bind has been declared as a resource on the usercontrol (it's a grid/textbox depending on the users selection).

If I change the code so that instead of a declared object, I create a new object and apply it to the property it works fine. It only happens when I try to bind objects that have already been declared on the XAML page

(I've also tried programatically setting ContentPresenter.Content instead of using a binding but it still throws the same error)

I've read somewhere that this is usually because a duplicate item exists in the visual tree - is it the case that objects declared and named in the resources section are already part of the visual tree? If so, how do I relocate these items so that they can appear on the actual page?

I don't want to be messing about with the opacity of the child controls etc - that should all be handled by the TransitionalContentPresenter

Any help would be much appreciated

        public DependencyObject SampleInformationContent
            get { return (DependencyObject)GetValue(SampleInformationContentProperty); }
            set { SetValue(SampleInformationContentProperty, value); }


Linq to SQL. VS2010.

I use the Attach method to attach and update entities coming back from client over WCF. This works fine.

However if I run Unit Test on the data access layer I get the 'System.NotSupportedException: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext.  This is not supported.'. This is correct, the unit test gets the entity directly from the data access layer and it is not detached.

So far I use helper method to detach (serialize/deserialize) the entity in my Unit Test class before I call the data access but this solution is not scalable.

The DataContext knows that the entity is already loaded/attached to another DataContext. How do I find the same???

I want to execute a method in my data access class and if the entity is loaded by another data context I will detach it so I can safely attach and update it.

Thank you.



I'm using Visual Studio 2010 against Word 2010 and I have building blocks (quick parts) with content controls in them. I would like to bind these content controls to data objects but apparently the process of saving the selection to the building block gallery strips out the databinding. I've tried programmatically adding it back after adding the quick part to the document, but I can't seem to get access to the content controls within the quick part (they are not in the this.Controls collection). Does anyone know of a way to get this done? If not, are there any suggestions? What I'm trying to do is set up a series of check boxes on the action pane that controls whether certain conent gets displayed or not. The content may contain a few editable regions and I want the user to be able to create the document entirely from the action pane if desired (although they should be able to edit those parts within the doc itself as well). So I'd like to be able to bind the editable parts to a data object. Any help would be greatly appreciated.




I have created a document with a lot of content control objects in the document. I am binding those content control items to a custom XML file. However, when I close out of the template, add a new custom XML file with new data (the purpose is to use the template to auto-gen some forms with different data), the content control objects all lose their font, style, size, everything. I have tried many ways of getting this to work, and they always come back with the font in Calibri size 11.


I saw some post a while back from like 2007 saying that this was a bug, but I was wondering if it has been fixed or patched, got dropped completely, or there is a workaround to this. It is really annoying to have a nicely formatted document, auto-gen some files using custom XML, and them all have the fonts/sizes messed up.







I have a problem with the memory consumption of my application when I have aforementioned DataGridViewComboBoxColumns in them. Here is how I basically create the ComboBox column


DataGridViewComboBoxColumn column = new


column.DataPropertyName = "OrderID";
column.DataSource = DataGet(_orderLookUp);
column.ValueMember = "OrderID";

column.DisplayMember = "OrderKey";


Now when I set a new DataSource on the DGV or update the table, which is the DataSource of the DGV, then the memory consumption of the application raises and stays up. According to what I have found out with the CLR Profiler this is due to DataGridViewRows residing in memory, which are referenced by DataGridViewComboBoxCells, which in term are referenced by some Eventhandler from a DataTable. I think that DataTable is the one, which is assigned to the Column for the lookup. And according to what I have found in the source of the DataGridViewComboBoxCell together with the "Who allocated" view of the CLR Profiler, it must be the Eventhandler, which is attached to the Disposed Event of the DataTable by the ComboBoxCell. It only seems to be unset and set when the DataSource of the cell is changed (via the Property) and I haven't found any other reference to it


I have tried explicitly setting the DataSource Property of the ComboBoxColumn to null before setting the DataSource of the DGV to the new table, but then I got exceptions during the rendering of the cell


DataGridViewComboBoxColumn col =
	(from DataGridViewColumn column in _treeGridView.Columns
	where column is DataGridViewComboBoxColumn
	select column).FirstOrDefault();

col.DataSource = null;

_treeGridView.DataSource = DataGet(_dataString);

Also tried it afterwards, but that didn't work either. On Setting the DataSource of the DGV all Boundcolumns are cloned and the old ones are deleted


Any suggestions? Of course, I'd be happy to provide more info


Thanks a lot





I am currently having an issue with allowing the user to add values to a databound combobox in a databound datagridview.

This is my validating event...

    private void dgvBbgCode_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
DataGridViewColumn column = dgvBbgCode.Columns[e.ColumnIndex];
if (column.GetType().Equals(typeof(DataGridViewComboBoxColumn)))
DataGridViewComboBoxColumn col = (DataGridViewComboBoxColumn) column;
object val = e.FormattedValue;
if (col.DisplayStyle == DataGridViewComboBoxDisplayStyle.ComboBox &&
IList<string> list = (IList<string>)col.DataSource;
if (!list.Contains(val.ToString()))
col.DataSource = list;
dgvBbgCode.CurrentCell.Value = e.FormattedValue;

The issue is that when the user moves out of the cell, although the new value is indeed added to the datasource, this update of the currentcell value sets it to be the first value in the list not the entered value. This differs from my previous attempt in which the value just reset to the original value on leaving the cell. However, when the user again clicks on the dropdown the value is set to the correct one in the list (the last item) probably courtesy of this code...

    private void dgvBbgCode_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
DataGridViewComboBoxEditingControl edit = (DataGridViewComboBoxEditingControl) e.Control;

if (edit.DataSource.GetType().Equals(typeof (BindingSource)))
edit.SelectedValue = dgvBbgCode.CurrentCell.Value;
edit.SelectedItem = dgvBbgCode.CurrentCell.Value;

switch (dgvBbgCode.CurrentCell.OwningColumn.Name)
case "securityDataGridViewTextBoxColumn":
case "fieldDataGridViewTextBoxColumn":
case "descriptionDataGridViewTextBoxColumn":
edit.DropDownStyle = ComboBoxStyle.DropDown;
edit.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
edit.DropDownStyle = ComboBoxStyle.DropDownList;
edit.DroppedDown = true;

What I want to know is how to properly set the value in the cell so that it persists? Clicking on a different value in the dropdown list sets it correctly it's just the textual entry method that fails. Entering some characters, selecting a value from the autocomplete list and tabbing also reverts to the original value. If I shift + tab back into the field and type again with autocomplete the value chosen the second time persists. I'm sure there's a better way of doing this but don't know how.


Recently i found the new chart control(part of 3.5 sp1) and started working with databinding. It seems following events are not triggering:
1) Databound
2) databindiing

however i can see post_paint event is firing.

Am i missing any thing?

Plz help.

I have this problem:
I want to create your custom labeled control.

It is grid with two cells. There is label in first cell and there is some control in second cell ( ContentPresenter to present control in derived controls).
I create base control CacheLabeledControl and i create ControlTemplate.

Now i derive CacheTextBox from CacheLabeledControl and create style base on CacheLabeled and set Content to TextBox

But it doesn't work. There is error 'Specified element is already the logical child of another element. Disconnect it first.'

What is wrong? Is any chance to change template in derived control or I have to have ControlTemplate for any derived custom control.

    xmlns:local="clr-namespace:Prosoft.WPF.TYPE" >
    <Style x:Key="{x:Type local:CacheLabeledControl}" TargetType="{x:Type local:CacheLabeledControl}">
        <Setter Property="Width" Value="Auto"/>
        <Setter Property="Height" Value="Auto"/>
        <Setter Property="IsEnabled" Value="{Binding Path=IsEnabled}"/>
        <Setter Property="HasError" Value="{Binding Path=HasError}"/>
        <Setter Property="Focusable" Value="False"/>
        <Setter Property="Template" >
                <ControlTemplate TargetType="{x:Type local:CacheTextBox}">
                     Background="{TemplateBinding Background}"
                     BorderBrush="{TemplateBinding BorderBrush}"
                     BorderThickness="{TemplateBinding BorderThickness}">

                        <Grid x:Name="PART_Grid" ShowGridLines="True">
                                <RowDefinition Height="Auto" />
                                <RowDefinition />
                                <RowDefinition Height="Auto" />
                                <RowDefinition Height="Auto" />
                                <ColumnDefinition Width="{TemplateBinding ColumnLabelWidth}" />
                                <ColumnDefinition />
                                <ColumnDefinition Width="Auto"/>
                            <Label Grid.Row="{TemplateBinding LabelPositionRow}"
                                   Grid.Column="{TemplateBinding LabelPositionColumn}"
                                   Content="{TemplateBinding LabelContent}"
                                   Width="{TemplateBinding ColumnLabelWidth}"
                                   HorizontalAlignment="{TemplateBinding LabelAlignment}" />
                            <ContentPresenter Grid.Row="1"

    <Style x:Key="{x:Type local:CacheTextBox}" TargetType="{x:Type local:CacheTextBox}"   BasedOn="{StaticResource {x:Type local:CacheLabeledControl}}">
        <Setter Property="Content">

Hi there,


Draw two rectangles
Group into a Canvas
Make canvas a control of type button (Right click menu method)
Notice that the button text (ContentPresenter) is in the upper left instead of centered in your new button.
This only happens in a Canvas, other containers it works correctly.

Can you not make buttons from a Canvas?  Is there a magic property somewhere that makes the contentpresenter correctly align to the center?

I have an ItemsControl in ItemsSource mode.  When I add an item to the source, a usercontrol is created from a datatemplate that corresponds to the item I just added.  The ItemsControl uses a canvas as it's ItemsPanel.  The problem is that when I inspect my code, I find that the children of my canvas are ContentPresenters, not my UserControl.  I would like to be able to access the particular UserControl in the canvas so I can use it's functionality.  Can anyone help me with this?

Hi Guys,

I've created a button style template as you can see below.  The animation on the foreground colour works as expected, however I'd like to modify the behaviour slightly to have the two events (MouseEnter and MouseLeave) fire on the Border element and not just the ContentPresenter.  Some of my content is quite short i.e. two letters - making the effective rollover area quite small (on a button of at least 160 width)  

Is there anyway I can get the Border's MouseEnter event to 'fire' the trigger in the same way the ContentPresenter does?

Many Thanks,


<ResourceDictionaryxmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><Stylex:Key="MenuButton"x:Name="NavButton"TargetType="{x:Type Button}"><SetterProperty="OverridesDefaultStyle"Value="True"/><SetterProperty="Background"Value="Transparent"/><SetterProperty="Foreground"Value="#006633"/><SetterProperty="BorderBrush"Value="#006633"/><SetterProperty="BorderThickness"Value="0,1,0,0"/><SetterProperty="FontFamily"Value="Cambria"/><SetterProperty="FontWeight"Value="Bold"/><SetterProperty="FontSize"Value="14"/><SetterProperty="MinHeight"Value="24"/><SetterProperty="MinWidth"Value="160"/><SetterProperty="Cursor"Value="Hand"/><SetterProperty="Template"><Setter.Value><ControlTemplateTargetType="Button"><BorderMargin="0,0,0,0"BorderBrush="{TemplateBinding BorderBrush}"BorderThickness="{TemplateBinding BorderThickness}"><ContentPresenterHorizontalAlignment="Center"VerticalAlignment="Center"/></Border><ControlTemplate.Triggers><EventTriggerRoutedEvent="Mouse.MouseEnter"><BeginStoryboardx:Name="storyButtonOver"><Storyboard><ColorAnimationStoryboard.TargetProperty="Foreground.Color"From="#006633"To="Black"Duration="0:0:0.5"/></Storyboard></BeginStoryboard></EventTrigger><EventTriggerRoutedEvent="Mouse.MouseLeave"><BeginStoryboard><Storyboard><ColorAnimationStoryboard.TargetProperty="Foreground.Color"From="Black"To="#006633"Duration="0:0:2.0"/></Storyboard></BeginStoryboard></EventTrigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style></ResourceDictionary>


i have some combo items that is getting items from Axapta. i want to display the items at runtime


Hello all.

I have a ContentPresenter that can hold any number of UserControls.  It doesn't necessarily know what UserControl is inside, but what UserControls can appear inside is controlled by the application.

I'd like detect a MouseDown event on the ContentPresenter level.  So, if a user clicks a Button that is defined in the UserControl I'd like it to bubble up to the ContentPresenter... but the Button appears to consume that event.

What is the best way to detect that a (normally) consumed MouseDown event several levels up the visual tree?



Hey Guys,

I'm working on a an application for Microsoft Surface.

I want to be able to detect contact events on an instance of the ContentPresenter class.

I can detect mouse and keyboard event, but not contact events. I'm thinking I solve this by creating a dummy class that extends the SurfaceUserControl and has an instance of ContentPresenter. So all I have to do in my main app is to call the dummy class and I will also be able to access contact events.

Sorry guys, I'm not a well versed programmer, forgive me if I have butchered some terminology.

BUT any help is much appreciated.




As explained in the subject I'm defining a DataTemplate for a ContentControl (or Button in the same way). When I add the ContentPresenter to the data template the IDE crashes with any exception message.


Do anybody know the cause or have the same problem?



I'm working a WPF application and currently working on some theming in Blend. I'm going for a dark theme and I've created a button template to use on buttons throughout the application, and the button is dark as well. The color of text in the Content property is black, and I want to change that to white so it's readable against the dark background. I think I should be able to do this within the template somewhere, but I can't find out where and Google is not getting me anywhere either.

Any clues?


I'm automating Wpf application and trying to read a text value from a row. The problem is UI Coded Test Builder does not detect the text block that is inside a Uia.ContentPresenter object. If anyone has a suggesstion, please let me know. Below is the Xaml that generates that column. Please let me know if I need to update my Xmal to access to the text block.

                            <GridViewColumn Controls:SortableListView.SortPropertyName="InvoiceAmount">

                                <GridViewColumnHeader HorizontalContentAlignment="Right">Invoice Amount</GridViewColumnHeader>



                                        <TextBlock TextAlignment="Right"

                                                   Text="{Binding Path=InvoiceAmount, StringFormat='{}{0:C}'}" />




Now there is a slightly different version of Xaml in the same application that I am able to access the textblock using search properties.

<GridViewColumn Controls:SortableListView.SortPropertyName="UserDescription"

                                                DisplayMemberBinding="{Binding Path=UserDescription}">

                                    <GridViewColumnHeader Name="gvchUserDescription">User Description</GridViewColumnHeader>


The application has been deployed to production and I don't have leverage to have my developers change Xaml structure at this point. They are willing to add AutomationIds if needed to the existing Xaml.

Any help would be highly appreciated.




I have a ListView with ContentPresenter binding to DataTemplate that have TextBox.....

so that the listview contains Textboxes that can accept values

Questions are

1) is it possible to maintain focus

2) how to validate each Textboxes


I have designed a complex DataTemplate to re-use among several ContentPresenters I have on a dialog. Within this DataTemplate I have a TextBox that is bound to a DependencyProperty of a custom UserControl. I'm having trouble setting the binding correctly to get updates reflected in my viewmodel. Setting the TextBox text from the property value works correctly, but not the other direction, updates when the user changes the text are not updating the source. I've created a small sample program to illustrate the issue.



          <TextBox x:Name="testTextBox" Height="28" 
            Text="{Binding Path=Title,
               RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType=TestBinding:CustomUC}, 
               Mode=TwoWay, UpdateSourceTrigger=LostFocus}"
          <TextBoxGrid.Row="1" Text=""/></Grid></StackPanel></DataTemplate><StyleTargetType="{x:Type TestBinding:CustomUC}"><SetterProperty="Template"><Setter.Value><ControlTemplateTargetType="{x:Type TestBinding:CustomUC}"><ContentPresenterx:Name="customCP"ContentTemplate="{StaticResource CustomUcTextBoxTemplate}"/></ControlTemplate></Setter.Value></Setter></Style></Window.Resources><StackPanel><Label>Does this work:</Label><ContentPresenterx:Name="theControl"HorizontalAlignment="Stretch"Content="{Binding Path=CustomUCItem}"/></StackPanel></Window>


MainWindow.xaml.cs: (only remarkable item is setting of DataContext)


using System.Windows;
namespace TestBinding
  ///<summary>/// Interaction logic for MainWindow.xaml///</summary>publicpartialclass MainWindow : Window
    public MainWindow()
      DataContext = new WindowViewModel();


namespace TestBinding
  class WindowViewModel
    private CustomUC _customUCItem;

    public WindowViewModel()
      CustomUCItem = new CustomUC("It works!");

    public CustomUC CustomUCItem
      get { return _customUCItem; }
      set { _customUCItem = value; }

And the custom UserControl, CustomUC.cs:

using System;
using System.Windows;
using System.Windows.Controls;

namespace TestBinding
  class CustomUC: UserControl
    publicstaticreadonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(CustomUC));
    publicstring Title
      get { return (string)GetValue(TitleProperty); }
      set { SetValue(TitleProperty, value);

    public CustomUC(string title)
      Title = title;

    privatevoid Update()                    
      Console.WriteLine("I Changed!");

The Update method is executed when the window is first loaded, but not when the user changes the TextBox contents. I've tried to attach a handler to the TextBox via code to force the Update method to be called, but I've had no luck getting a hold of it via code. I've tried the following, among other things:

publicoverridevoid OnApplyTemplate()
      ContentPresenter cp = (ContentPresenter) (this.Template.FindName("customCP",this));
      DataTemplate dt = cp.ContentTemplate as DataTemplate;
      TextBox tb = dt.FindName("testTextBox", cp) as TextBox;

but this comes back with the dreaded "This operation is valid only on elements that have this template applied ."  I also tried:

      TextBox tb = dt.FindName("testTextBox", this) as TextBox;

with the same result. Frustrating as I can drill down in the debugger through the CustomUC members and see the TextBox in the XAML nodes list, in a non-public member, but I can't seem to find the right incantation to get to it.

Help appreciated.




<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure