我创建了一个自定义控件,允许使用 Thumb 控件的 DragDelta 进行拖动。我希望能够在自定义控件 ContentPresenter 中插入 Shape、Image 或 TextBlock。
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>
最佳答案
自 Content
属性是 Object
,您可以在其中放入 ContentControl
中的任何内容。 :可视化树元素、字符串、具有隐式 View 模型 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 在<Thumb...
下给了我一个蓝色的曲线。在 XAML 中,因为 TargetType
ControlTemplate
的不匹配,但它构建并运行良好。对模板的此更改将消除该问题:
<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
}
}
关于c# - 使用 ContentPresenter 进行自定义控件 (Thumb),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39518570/