'WPF bind to content control's content property

How can I bind to content control's content property ?
I'v created custom control :

      public class CustomControl 
        {
         // Dependency Properties
public int MyProperty
        {
            get { return (int)GetValue(MyPropertyProperty); }
            set { SetValue(MyPropertyProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register("MyProperty", typeof(int), typeof(MainViewModel), new PropertyMetadata(0));
         }

In ViewModel I created a property of type of this custom control :

    public CustomControl CustomControl { get; set; }

In view I bind this property to content control :

     <ContentControl x:Name="Custom" Content="{Binding CustomControl}"></ContentControl>

Now how can I bind to content control's content property?



Solution 1:[1]

<ContentControl Content="{Binding ElementName=Custom, Path=Content}" />

I'm not sure what effect this will have though. I have a suspicion it will complain about UI elements already having a parent or something similar.

Update

If I think I understand your question correctly I don't think you can do what you want using bindings. This is an alternative which adds a callback for when the content is changed so you can set the new content to the property of your VM:

class CustomControl : Control
{
    static CustomControl()
    {
        ContentControl.ContentProperty.OverrideMetadata(typeof(CustomControl), new PropertyMetadata(null, UpdateViewModel));
    }

    private static void UpdateViewModel(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var control = d as CustomControl;
        var viewModel = control.DataContext as MyViewModel;
        viewModel.CustomControl = control;
    }
}

You'll probably want some error handling in there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1