使用ContentPresenter进行自定义控件(Thumb)

时间:2016-09-15 19:05:11

标签: c# wpf

我创建了一个自定义控件,允许使用Thumb控件的DragDelta进行拖动。我希望能够在自定义控件ContentPresenter中插入Shape,Image或TextBlock。

CustomControl.xaml(Thumb)

<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>

2 个答案:

答案 0 :(得分:2)

由于Content属性为Object,您可以在ContentControl中放置任何内容:可视树元素,字符串,带隐式{{1}的视图模型(在这个特殊情况下相当牵强,但这是事情的原理) - 你说出来。

MyThumb.xaml

DataTemplate

VS在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> 下给我一个蓝色的波形,因为<Thumb...的{​​{1}}并不匹配,但是它构建并且工作正常。对模板的这一更改将消除:

TargetType

MyThumb.xaml.cs

ControlTemplate

答案 1 :(得分:0)

归功于Ed Plunkett

CustomControl.xaml.cs(Thumb)

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

    public FrameworkElement Content { get; set; }
}
相关问题