#1,182 – Using RenderSize Properties in Custom Elements

When writing rendering code for a custom element that derives from FrameworkElement, you can use the ActualWidth and ActualHeight properties to know how to render the element.  These properties indicate the desired final size of the element, after all layout calculations have been done.

    public class MyFrameworkElement : FrameworkElement
    {
        protected override void OnRender(DrawingContext dc)
        {
            dc.DrawLine(new Pen(Brushes.Blue, 2.0),
                new Point(0.0, 0.0),
                new Point(ActualWidth, ActualHeight));
            dc.DrawLine(new Pen(Brushes.Green, 2.0),
                new Point(ActualWidth, 0.0),
                new Point(0.0, ActualHeight));
        }
    }

If a custom control derives from UIElement, it won’t have access to the ActualWidth and ActualHeight properties, but can instead use RenderSize.Width and RenderSize.Height.  (You can also use these properties from within an element that derives from FrameworkElement, since FrameworkElement inhertis from UIElement).

    public class MyUIElement : UIElement
    {
        protected override void OnRender(DrawingContext dc)
        {
            dc.DrawLine(new Pen(Brushes.Blue, 2.0),
                new Point(0.0, 0.0),
                new Point(RenderSize.Width, RenderSize.Height));
            dc.DrawLine(new Pen(Brushes.Green, 2.0),
                new Point(RenderSize.Width, 0.0),
                new Point(0.0, RenderSize.Height));
        }
    }

#1,177 – UIElement vs. FrameworkElement vs. Control

If you want to implement a custom element in WPF, either to display something in a user interface or to get input from a user, you’ll typically derive your custom element from one of the following classes: UIElementFrameworkElement, or Control.

The inheritance chain for these three classes is:

1177-001

When creating a custom control, you’ll want to choose as a base class whichever one of these classes has only the features that you want.  The core functionality for these three classes is:

  • UIElement  (Layout + Input + Focus + Events)
    • Layout behavior (parent/child relationship, measure/arrange passes)
    • Responding to user input (input events, command bindings)
    • Managing focus
    • Raising and responding to routed events
  • FrameworkElement adds
    • Alignment-related and Margin properties
    • Animation support
    • Data binding
    • Data templates
    • Styles
    • Defaults Focusable to false
  • Control adds
    • Control templates
    • Background, Foreground
    • Font-related properties
    • Border-related properties
    • Defaults Focusable to true

#972 – How ListBox Items Are Rendered

The rules for how WPF will render items contained in a ListBox are as follows:

  • If the item derives from UIElement, it is rendered normally, using the layout system
  • Otherwise, the item’s ToString method is called and the resulting string is displayed

In the example below, the first two items in the ListBox derive from UIElement and are therefore rendered as controls.  The third item is a simple .NET object, so its ToString method is called.

        <ListBox Margin="15" Width="250" Height="250">
            <TextBox Text="Enter text here" Width="150"/>
            <Label Content="A label" FontFamily="Times New Roman"
                   FontSize="16"/>
            <local:Actor FullName="Marty Feldman" BirthYear="1934" DeathYear="1982"/>
        </ListBox>

972-001

#713 – Setting the Cursor to an Image of an UIElement While Dragging

You can use the GiveFeedback to change the cursor during a drag-and-drop operation.  You can go a bit further and set the cursor to an image that represents the user interface element that you are dragging by rendering the UIElement to a bitmap and then converting that bitmap to a cursor.

This example is based on code written by Brandon Cannaday, at http://www.switchonthecode.com/tutorials/wpf-tutorial-how-to-use-custom-cursors .  To start with, here is Brandon’s code, as modified by reader “Swythan”:

    public class CursorHelper
    {
        private static class NativeMethods
        {
            public struct IconInfo
            {
                public bool fIcon;
                public int xHotspot;
                public int yHotspot;
                public IntPtr hbmMask;
                public IntPtr hbmColor;
            }

            [DllImport("user32.dll")]
            public static extern SafeIconHandle CreateIconIndirect(ref IconInfo icon);

            [DllImport("user32.dll")]
            public static extern bool DestroyIcon(IntPtr hIcon);

            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);
        }

        [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
        private class SafeIconHandle : SafeHandleZeroOrMinusOneIsInvalid
        {
            public SafeIconHandle()
                : base(true)
            {
            }

            override protected bool ReleaseHandle()
            {
                return NativeMethods.DestroyIcon(handle);
            }
        }

        private static Cursor InternalCreateCursor(System.Drawing.Bitmap bmp)
        {
            var iconInfo = new NativeMethods.IconInfo();
            NativeMethods.GetIconInfo(bmp.GetHicon(), ref iconInfo);

            iconInfo.xHotspot = 0;
            iconInfo.yHotspot = 0;
            iconInfo.fIcon = false;

            SafeIconHandle cursorHandle = NativeMethods.CreateIconIndirect(ref iconInfo);
            return CursorInteropHelper.Create(cursorHandle);
        }

        public static Cursor CreateCursor(UIElement element)
        {
            element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            element.Arrange(new Rect(new Point(), element.DesiredSize));

            RenderTargetBitmap rtb =
              new RenderTargetBitmap(
                (int)element.DesiredSize.Width,
                (int)element.DesiredSize.Height,
                96, 96, PixelFormats.Pbgra32);

            rtb.Render(element);

            var encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(rtb));

            using (var ms = new MemoryStream())
            {
                encoder.Save(ms);
                using (var bmp = new System.Drawing.Bitmap(ms))
                {
                    return InternalCreateCursor(bmp);
                }
            }
        }
    }

Now that we have the helper class, we can use it to set the cursor to the image of a Label that we are dragging. Here’s the XAML defining a label to drag from and one to drag to.

    <StackPanel Orientation="Vertical" HorizontalAlignment="Center" Margin="45">
        <Label Content="Data to drag" Background="AliceBlue" Padding="15,10"
               MouseLeftButtonDown="Label_MouseLeftButtonDown"
               GiveFeedback="Label_GiveFeedback"/>
        <Label Content="Drag to here" Background="MediumSpringGreen" Padding="15,10" Margin="20"
               AllowDrop="True" Drop="Label_Drop"/>
    </StackPanel>

Here’s the relevant drag-and-drop related code:

        private void Label_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DataObject data = new DataObject(DataFormats.Text, ((Label)e.Source).Content);

            DragDrop.DoDragDrop((DependencyObject)e.Source, data, DragDropEffects.Copy);
        }

        private void Label_Drop(object sender, DragEventArgs e)
        {
            ((Label)e.Source).Content = (string)e.Data.GetData(DataFormats.Text);
        }

        private Cursor customCursor = null;

        private void Label_GiveFeedback(object sender, GiveFeedbackEventArgs e)
        {
            if (e.Effects == DragDropEffects.Copy)
            {
                if (customCursor == null)
                    customCursor = CursorHelper.CreateCursor(e.Source as UIElement);

                if (customCursor != null)
                {
                    e.UseDefaultCursors = false;
                    Mouse.SetCursor(customCursor);
                }
            }
            else
                e.UseDefaultCursors = true;

            e.Handled = true;
        }

#251 – Embedding an UIElement Within a FlowDocument

You can embed any UIElement into a FlowDocument using the BlockUIContainer block type.  This allows inserting controls into the middle of a document.  Note that since Panel derives from UIElement, you can embed not just single controls, but containers that host other controls.

Here’s an example.

	<FlowDocument FontFamily="Cambria" FontSize="14">
		<Paragraph>"Be who you are and say what you feel, because those who mind don't matter, and those who matter don't mind.
			— Dr. Seuss</Paragraph>
		<BlockUIContainer FontFamily="Arial" FontSize="12">
			<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
				<Button Content="Like it" Margin="10" Width="70" Height="25"/>
				<Button Content="Don't like it" Margin="10" Width="70" Height="25"/>
			</StackPanel>
		</BlockUIContainer>
		<Paragraph>We continue this document with some more lovely Dr. Seuss quotes..</Paragraph>
	</FlowDocument>

The document will look like this at runtime:

#180 – How Layout Works

Layout in WPF is the process by which a container (e.g. Grid, StackPanel) arranges its child elements (e.g. Button, Label).  The container figures out the final size and position of each child element, which dictates how the container’s children will be rendered.

The layout process is triggered when a container is first being rendered or when a property on a child control changes (if that property can affect layout).

Layout is basically a conversation between the container and its children.  This conversation consists of two phases:

  • Measure – Container asks each child what its desired size is
  • Arrange – Container figures out how to arrange its children and decides on final position and size of each child

How a container arranges its children is dependent on the specific class.  E.g. A Grid puts its children in rows and columns, while a StackPanel stacks children horizontally or vertically.

#170 – Functionality That The Base Element Classes Provide

The four main base element classes in WPF each provide slightly different functionality, above and beyond DependencyObject, which they all inherit from, directly or indirectly.

  • ContentElement adds (to DependencyObject)
    • Input events and commanding
    • Focus
    • Raise and respond to routed events
    • Animation support
  • FrameworkContentElement adds (to ContentElement)
    • Additional input elements (e.g. tooltips, context menus)
    • Storyboards
    • Data binding
    • Styles
    • Property value inheritance
  • UIElement adds (to DependencyObject)
    • via Visual
      • Hit testing
      • Clipping and coordinate transformations
      • Participation in visual tree via parent/child relationships
    • Layout behavior (measure/arrange)
    • Input events and commanding
    • Focus
    • Raise and respond to routed Events
    • Animation support
  • FrameworkElement adds (to UIElement)
    • Additional input elements (e.g. tooltips, context menus)
    • Storyboards
    • Data binding
    • Styles
    • Property value inheritance
    • Support for the logical tree