Search code examples
c#wpfdependencyobject

Create a DependencyObject that "accepts" direct content


I'm creating a custom time that should be used in an empty XAML file:

<windows:BlackAndWhiteWindow x:Class="GSdk.Shared.Windows.TestWindow"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:windows="clr-namespace:GSdk.Shared.Windows"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <windows:AnotherDependencyObject>A string</windows:AnotherDependencyObject>
</windows:BlackAndWhiteWindow>

How can I effectively allow my custom class BlackAndWhite window (which inherits from DependencyObject and IDisposable) to allows accept those defined from visual studio as "direct content"?


Solution

  • You need to mark one of the properties of BlackAndWhiteWindow class as a "content" property. You can do it by applying the ContentPropertyAttribute.

    See the following link for details on how to create XAML-friendly types: http://msdn.microsoft.com/en-us/library/ms753379.aspx

    Another option (preferred) is to inherit you class from one of the WPF base classes, e.g. ContentControl or ItemsControl. They already have all the infrastructure and properties in place.