我是创建 UserControl 的新人,现在我正在尝试自定义 UserControl 模板,如下所示:
<UserControl x:Class="WpfApplication1.PieButton"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" Loaded="OnLoaded">
<UserControl.Template>
<ControlTemplate>
<Path Name="path" Stroke="Aqua" StrokeThickness="3">
<Path.Fill>
<SolidColorBrush Color="{TemplateBinding Fill}" />
</Path.Fill>
<Path.Data>
......
</UserControl>
同时我在后端代码中创建了依赖属性:
public partial class PieButton : UserControl
{
public PieButton()
{
InitializeComponent();
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
}
public Color Fill
{
get { return (Color)GetValue(FillProperty); }
set { SetValue(FillProperty, value); }
}
public static readonly DependencyProperty FillProperty =
DependencyProperty.Register("Fill", typeof(Color), typeof(PieButton));
......
我想TemplateBinding
在 XAML 中使用绑定Fill
我的 PieButton 的属性来填充路径对象。Visual Studio 设计器警告我“无法访问或识别 Fill 属性”。
根据我的理解,TemplateBinding
从应用这个ControlTemplate的元素中找到属性名,应该是PieControl
在这里,但是为什么Fill
Property不能在这里访问呢?
顺便提一句,
我测试了以下绑定,它可以为我工作
Color="Binding Fill,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}}"
但是我还是觉得TemplateBinding应该可以在这种场景下工作,所以请在这里指出我的错。谢谢。