#836 – Setting a ContentControl’s Content to a CLR Object
June 6, 2013 1 Comment
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(); }