为自定义控件(拇指)使用ContentPresenter

本文关键字:使用 ContentPresenter 拇指 自定义控件 | 更新日期: 2023-09-27 18:07:07

我创建了一个允许使用拇指控件的DragDelta拖动的自定义控件。我想能够插入一个形状,图像或TextBlock内的自定义控件ContentPresenter。

CustomControl。xaml(拇指)

<Thumb x:Class="StackOverflow.CustomControl"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Thumb.Template>
        <ControlTemplate>
            <ContentPresenter/>
        </ControlTemplate>
    </Thumb.Template>
</Thumb>

MainWindow.xaml

<Window x:Class="StackOverflow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:StackOverflow">
    <local:CustomControl>
        <!--Shape, Image or TextBlock-->
    </local:CustomControl>
</Window>

为自定义控件(拇指)使用ContentPresenter

由于Content属性是Object,您可以在那里放置任何将进入ContentControl的内容:可视树元素,字符串,具有隐式DataTemplate的视图模型(在此特定情况下相当遥远,但这是事情的原则)-您命名它。

MyThumb.xaml

<Thumb 
    x:Class="ThumbTest.MyThumb"
    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:thumb="clr-namespace:ThumbTest"
    mc:Ignorable="d" 
    d:DesignHeight="300" 
    d:DesignWidth="300"
    >
    <Thumb.Template>
        <ControlTemplate TargetType="thumb:MyThumb">
            <ContentPresenter 
                />
        </ControlTemplate>
    </Thumb.Template>
</Thumb>

VS在XAML中给我<Thumb...下的蓝色曲线,因为ControlTemplateTargetType不匹配,但它构建和工作得很好。对模板的更改将消除:

<Thumb.Template>
    <ControlTemplate TargetType="thumb:MyThumb">
        <ContentControl
            Content="{Binding Content, RelativeSource={RelativeSource AncestorType=thumb:MyThumb}}"
            />
    </ControlTemplate>
</Thumb.Template>

MyThumb.xaml.cs

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Markup;
namespace ThumbTest
{
    [ContentProperty("Content")]
    public partial class MyThumb : Thumb
    {
        public MyThumb()
        {
            InitializeComponent();
        }
        #region Content Property
        public Object Content
        {
            get { return (Object)GetValue(ContentProperty); }
            set { SetValue(ContentProperty, value); }
        }
        public static readonly DependencyProperty ContentProperty =
            DependencyProperty.Register("Content", typeof(Object), typeof(MyThumb),
                new PropertyMetadata(null));
        #endregion Content Property
    }
}

感谢Ed Plunkett

CustomControl.xaml.cs(拇指)

[ContentProperty("Content")]
public partial class CustomControl : Thumb
{
    public CustomControl()
    {
        InitializeComponent();
    }
    public FrameworkElement Content { get; set; }
}