gpt4 book ai didi

c# - 将 ContentPresenter 用于自定义控件 (Thumb)

转载 作者:行者123 更新时间:2023-11-30 23:21:00 25 4
gpt4 key购买 nike

我创建了一个允许使用 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 : 视觉树元素、字符串、带有隐式 DataTemplate 的 View 模型(在这种特殊情况下相当牵强,但这是事情的原则) - 你的名字。

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 中,因为 TargetTypeControlTemplate不匹配,但它构建并工作正常。对模板的这种更改将摆脱它:

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com