找不到自定义wpf控件的属性模板

时间:2011-07-31 10:58:51

标签: wpf wpf-controls

我正在尝试修改http://www.hardcodet.net/projects/wpf-notifyicon

上的wpf托盘图标

目标是有一个单独的xaml文件,用于定义具有特定配置的trayicon,以便可以在单独的文件中轻松添加此配置以表示wpf窗口。

我对wpf非常新,但我试图在ResourceDictionary中使用ControlTemplate来实现目标:

指向App.xaml中的资源

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="trayicon.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

trayicon.xaml的分离配置

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:tb="clr-namespace:Hardcodet.Wpf.TaskbarNotification">
<ControlTemplate x:Key="TrayIcon" TargetType="{x:Type tb:TaskbarIcon}">
            <tb:TaskbarIcon x:Name="MyNotifyIcon"
        IconSource="/TaskbarNotification/DefaultTrayIcon.ico"
        ToolTipText="I am notified yes!"
        MenuActivation="LeftOrRightClick"></tb:TaskbarIcon>
</ControlTemplate>
</ResourceDictionary>

尝试使用配置

<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    xmlns:tb="clr-namespace:Hardcodet.Wpf.TaskbarNotification"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <tb:TaskbarIcon Template="{StaticResource TrayIcon}"></tb:TaskbarIcon>
</Grid>
</Window>

MainWindow.xaml

中抛出异常

在'TaskbarIcon'

类型中找不到属性'Template'

我的猜测是我必须向这个自定义wpf控件添加一些代码,woudl公开Template属性并设置它应该如何设置? 但我不知道我会怎么做,你能指出我正确的方向吗?

需要代码的狂野部分猜测

public static readonly DependencyProperty TemplateProperty =
    DependencyProperty.Register("Template",
                                typeof (SomeTemplateType),
                                typeof (TaskbarIcon),
                                new FrameworkPropertyMetadata(SomeTemplateType.Empty, TemplatePropertyChanged));

[Category(CategoryName)]
[Description("Enables Templating.")]
public SomeTemplateType Template
{
  get { return (SomeTemplateType)TemplateProperty; }
  set { SetValue(TemplateProperty,value); }
}

1 个答案:

答案 0 :(得分:2)

Cel我首先不了解模板。控件模板的目标是tb:TaskbarIcon实际上有另一个tb:TaskbarIcon里面!!!

我假设您希望在应用程序中使用指定的值将以下属性应用于TrayIcons ...

     IconSource="/TaskbarNotification/DefaultTrayIcon.ico";
     ToolTipText="I am notified yes!";
     MenuActivation="LeftOrRightClick"

如果那样,那么假设上面的属性是依赖属性,而不是创建一个控件模板,为什么不创建一个针对tb的样式:TaskbarIcon并指定Setters,它将上面的属性设置为相应的值。

   <Style x:Name="MyNotifyIcon" TargetType="{x:Type tb:TaskbarIcon}">
        <Setter Property="IconSource" Value="/TaskbarNotification/DefaultTrayIcon.ico"/>
        <Setter Property="ToolTipText" Value="I am notified yes!" />
        <Setter Property="MenuActivation" Value="LeftOrRightClick" />
  </Style>

然后将此样式应用于TaskbarIcon

  <tb:TaskbarIcon Style="{StaticResource MyNotifyIcon}"></tb:TaskbarIcon>

所以基本上如果这是你正在寻找的,那么模板是不可能的。 请建议这是否有帮助。