#836 – Setting a ContentControl’s Content to a CLR Object

You’ll typically set the Content property of a content control to an instance of an UIElement, which will typically include one or more controls.  (E.g. On a Button).

You can also set a Content property to a plain CLR object, i.e. an object that derives from System.Object.  When you do this, a content control will render the object by calling its ToString method.

In the example below, a Tooltip’s content is set to an instance of a Dog class.  When the tooltip is displayed, the dog’s ToString method is called.

<Window.Resources>
    <local:Dog x:Key="myDog" Name="Kirby" Age="15" FavToy="Tennis ball"/>
</Window.Resources>

<StackPanel DataContext="{StaticResource myDog}">
    <Label Content="{Binding Name}" Margin="10"
           ToolTip="{Binding}"/>
</StackPanel>

Assume that the ToString method dumps out the contents of the object:

        public override string ToString()
        {
            StringBuilder sbValue = new StringBuilder(string.Format("Dog {0}:\n", Name));
            sbValue.AppendFormat("  Age: {0}\n", Age);
            sbValue.AppendFormat("  Favorite Toy: {0}\n", FavToy);

            return sbValue.ToString();
        }

836-001

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #836 – Setting a ContentControl’s Content to a CLR Object

  1. Pingback: Dew Drop – June 6, 2013 (#1,562) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: