property Template not found for custom wpf control - wpf

I am trying to modify the wpf tray icon at http://www.hardcodet.net/projects/wpf-notifyicon
the aim is to have a separate xaml file that would define a trayicon with a specific configuration, so that this configuration, in a separate file, could be easily added to say a wpf window.
im very new to wpf, but am trying to use ControlTemplate in a ResourceDictionary to achieve the aim:
Pointing to resource in App.xaml
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="trayicon.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
The separated configuration of 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>
Trying to use the configuration
<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>
Exception thrown in MainWindow.xaml
The property 'Template' was not found in type 'TaskbarIcon'
My guess is that i have to add some code to this custom wpf control that woudl expose the Template property and set it how it should be set?
But i have no idea how i would do that, could you point me in the right direction please?
Wild partial guess of code needed
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); }
}

Cel I dont understand the template in the first place. The control template is targetted for tb:TaskbarIcon which actually has another tb:TaskbarIcon inside it!!!
I assume you want following properties to be applied to TrayIcons across your application with their specified values...
IconSource="/TaskbarNotification/DefaultTrayIcon.ico";
ToolTipText="I am notified yes!";
MenuActivation="LeftOrRightClick"
If thats so then assuming that above properties are dependency properties, instead of creating a control template why dont you create a style which is targetted to tb:TaskbarIcon and specify Setters which set the above properties with their corresponding values.
<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>
Then apply this style to your TaskbarIcon
<tb:TaskbarIcon Style="{StaticResource MyNotifyIcon}"></tb:TaskbarIcon>
So basically if this is what you are looking for, then template is out of question.
Please suggest if this helps you.

Related

Is it valid to use a Blend d:Style.DataContext inside WPF resource dictionary?

When defining WPF styles, I often use the Expression Blend <d:Style.DataContext> tag to let Intellisense know what the runtime DataContext will be. It works great. Unfortunately I cannot seem to make this work in a resource dictionary and I am unclear as to why.
For example, here in a style for a RadTabItem, I tell Intellisense that SettingsPageVm will be the DataContext:
<UserControl x:Class="Views.ConfigureView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:tk="http://schemas.telerik.com/2008/xaml/presentation"
xmlns:viewModels="clr-namespace:ViewModels"
d:DataContext="{d:DesignInstance viewModels:ConfigureVm}">
<Grid>
<tk:RadTabControl ItemsSource="{Binding Categories}" >
<tk:RadTabControl.Resources>
<!-- Tell setters that SettingsPageVm will be the datacontext -->
<Style TargetType="{x:Type tk:RadTabItem}">
<d:Style.DataContext>
<x:Type Type="viewModels:SettingsPageVm" />
</d:Style.DataContext>
<!-- (Imagine many setters here, binding to SettingsPageVm) -->
This works fine.
But if try I move that same style to a separate ResourceDictionary Visual Studio complains. The editor puts a blue squiggly underneath the d:Style.DataContext declaration and highlights it red. The compiler complains about it as follows:
1>I:\Dev\MyApp\Resources\Styles\DialogStyles.xaml(13,14): error
MC4004: Style cannot contain child 'TypeExtension'. Style child must
be a Setter because it is added to the Setters collection. Line 13
Position 14.
Why is this valid in one context and not valid in another?
<ResourceDictionary 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:viewModels="clr-namespace:ViewModels"
xmlns:tk="http://schemas.telerik.com/2008/xaml/presentation"
>
<Style x:Key="SettingsPageTabStyle" TargetType="{x:Type tk:RadTabItem}">
<d:Style.DataContext> <!-- *** ERROR *** -->
<x:Type Type="viewModels:SettingsPageVm" />
</d:Style.DataContext>
</Style>
</ResourceDictionary>
Answering my own question because half a day later I stumbled on it.
I had neglected to add the
mc:Ignorable="d"
line to my XAML. Once I did that, everything worked fine.
(Just One of those obscure WPF lessons that I am sure I already learned and then forgot at least once before -- maybe twice -- in the past over several years of working on WPF. )

Use Resource Dictionary Styles in my class library project without merging dictionaries

I am creating a class library project that will contain WPF user controls. My Requirement is that all controls have the same style. My project looks like:
Things I have done in order to solve this problem:
Added all references needed by a WPF application System.Xaml, WindowsBase, etc.. so that I can have wpf controls in my class library project.
In AssemblyInfo.cs I have added:
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
Added ResourceDictionary1.xaml To the project adding the style.
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="Brush1" Color="#FF19199E"/>
</ResourceDictionary>
Now if I want to use a style on my UserControl1.xaml I do:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ResourceDictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Grid >
<Rectangle Fill="{StaticResource Brush1}" />
</Grid>
I know it works great but here is the catch. Every time I create a new userControl I will have to merge the dictionary. On a regular WPF application I could just merge the dictionary once on App.xaml and I will be able to use that dictionary on my entire application. How can I avoid having to merge the dictionary every time I create a new userControl? If I plan on addying a new resource dictionary I will have to go to all userControls and merge another dictionary. Perhaps I wrote the question title incorrectly and my question should have been how can I add a App.xaml file to a class library project
You should replace the source value ResourceDictionary1.xaml like the follow:
Source="pack://application:,,,/ControlsDLL;component/ResourceDictionary1.xaml">
or just simple as following:
<UserControl.Resources>
<ResourceDictionary Source="pack://application:,,,/ControlsDLL;component/ResourceDictionary1.xaml"></ResourceDictionary>
</UserControl.Resources>

How can data templates in generic.xaml get applied automatically (redux)?

This is a follow-up to a question posted by Thiado de Arruda. In short, he wanted to have a DataTemplate in his generic.xaml file, but the template wasn't being applied.
The answer given suggested placing the DataTemplate in the ControlTemplate.Resources for the control that hosted his custom type. This works very well, however, suppose that he needed the DataTemplate to apply in other places, not just within the host control. Would it be necessary to copy the DataTemplate to the ControlTemplates of every other host control?
Edit (restating question):
I am developing a WPF application using MVVM design principles. MainWindow.xaml contains the structure of the UI, and all of the styling is coded in Themes\generic.xaml. (The behavior is coded in a separate view model class, but that's irrelevant.) As part of the UI, I created a subclass of ListBox (MyListBoxSubClass) to display a collection of an ordinary .Net object of my own creation (MyObject). MyListBoxSubClass has a style in generic.xaml that redefines the Template property, and it gets applied as expected. I also have a DataTemplate for MyObject in generic.xaml, but this does not get applied. According to the above link, I have to place the DataTemplate in the Resources collection of the ControlTemplate for MyListBoxSubClass in order for this DataTemplate to be applied. This works wonderfully.
My question is how to get the DataTemplate to apply to MyObject everywhere in my application without having to duplicate the DataTemplate? I've tried adding a key to the DataTemplate and referencing it where I need it, but for some reason, I get a XAML parse error at runtime, and Resharper says that it can't resolve my DataTemplate key.
Add the data template in a separate resource dictionary in another XAML file.
Bring the XAML file into your generic.xaml control template resources:
<ControlTemplate ...>
<ControlTemplate.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="wherever.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</ControlTemplate.Resources>
</ControlTemplate>
Then wherever else you want to use this data template, you can bring it into merged dictionary of resources of wherever you want - user control, window, another control template, etc...
<Window x:Name="someWindow">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="wherever.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
</Window>
Hope this helps.

WPF Dynamic Resource Lookup Behavior with FixedPage

Having the following very simple xaml:
<DocumentViewer Name="dv">
<FixedDocument Name="fd" Loaded="fd_loaded">
<FixedDocument.Resources>
<Style x:Key="TestStyle">
<Style.Setters>
<Setter Property="TextBlock.Foreground" Value="BlueViolet"/>
</Style.Setters>
</Style>
<SolidColorBrush x:Key="foregroundBrush" Color="Orange"/>
</FixedDocument.Resources>
<PageContent Name="pc">
<FixedPage Name="fp" Width="800" Height="600" Name="fp">
<TextBlock Name="tb" Style="{DynamicResource TestStyle}">
Lorem ipsum
</TextBlock>
<TextBlock Foreground="{DynamicResource foregroundBrush}" Margin="20">
Lorem ipsum
</TextBlock>
</FixedPage>
</PageContent>
</FixedDocument>
</DocumentViewer>
The use of Dynamic Resources (which I actually need in a more complex situation) here doesn't work. Using Static Resources colors the TextBlocks in the desired colors. Moving the Resources to the level of the FixedPage also does the trick. But I would like to have one generic resource dictionary on a top level element (because of runtime changes the user can make for colours, fonts, etc.). Placing the resources on Application level also does work. But it's not an option for good reasons.
Anybody have any clue why this doesn't work. Does it have something to do with the Logical Tree from the TextBlock upwards?
MSDN Resources Overview states that:
The lookup process checks for the requested key within the resource dictionary defined by the element that sets the property.
If the element defines a Style property, the Resources dictionary within the Style is checked.
If the element defines a Template property, the Resources dictionary within the FrameworkTemplate is checked.
The lookup process then traverses the logical tree upward, to the parent element and its resource dictionary. This continues until the root element is reached.
I also tried putting the Brush and the Style into the Resources of a (dummy) Style according to the above explanation of MSDN. But that didn't work either.
Really have the feeling that this can not be that complex, but most probably I oversee something. Any help is appreciated.
EDIT
When naming the TextBlock to "tb" and then using tb.FindResource("TestStyle") throws an exception. So that resource clearly can't be found. If I check out LogicalTreeHelper.GetParent(tb) and repeat that for the parents found I get the expected result: TextBlock > FixedPage > PageContent > FixedDocument ...
EDIT2
This works perfect. What's the difference with the XAML projected earlier?
<Window x:Class="WpfDynamicStyles2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<SolidColorBrush x:Key="resBrush" Color="Orange"></SolidColorBrush>
</Grid.Resources>
<StackPanel>
<Button>
<TextBlock Foreground="{DynamicResource resBrush}">Dummy text...</TextBlock>
</Button>
</StackPanel>
</Grid>
</Window>
EDIT3
private void fd_Loaded(object sender, RoutedEventArgs e)
{
Object obj = pc.TryFindResource("foregroundBrush");
obj = fp.TryFindResource("foregroundBrush");
obj = tb.TryFindResource("foregroundBrush");
}
The dynamic resource placed on the Foreground property of the textbox cannot be resolved (the actual resource is at the FixedDocument.Resources level). Also using the TryFindResource in code behind works from pc (PageContent) but from fp (FixedPage) and tb (TextBlock) it cannot resolve the resource (obj is null). When using a Static Resource in the XAML Markup everything works fine.
Well going the style way is a good design but not necessary. To make dynamic color based same named (keyed) brushes, we can use as dynamic color dictionaries (NOT brush dictionaries)
The solution can be as below ...
Create a single brush resource dictionary.
Refer the color in the brush with DynamicResource attribute.
Create multiple resource dictionaries with same keyed Color resource in each of them them.
Based on user's requirement, clear and add into Application.Current.resources.MergedDictionaries.
Example
Make a WPF project with a window that has following XAML....
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Window11Resources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<DockPanel LastChildFill="True">
<ComboBox DockPanel.Dock="Top" VerticalAlignment="Top"
SelectionChanged="ComboBox_SelectionChanged"
SelectedIndex="0">
<ComboBox.ItemsSource>
<Collections:ArrayList>
<System:String>Orange</System:String>
<System:String>Red</System:String>
<System:String>Blue</System:String>
</Collections:ArrayList>
</ComboBox.ItemsSource>
</ComboBox>
<DocumentViewer>
<FixedDocument>
<PageContent>
<FixedPage Width="793.76" Height="1122.56">
<TextBlock
FontSize="30"
Foreground="{StaticResource LabelColorBrush}"
Text="Test"/>
</FixedPage>
</PageContent>
</FixedDocument>
</DocumentViewer>
If you observe the window doesnt need to use anything which is dynamic. All refernces can remain static. So LabelColorBrush can be found in dictionary Window11Resources.xaml
In Window11Resources.xaml dictionary add a dynamic color brush.
<SolidColorBrush x:Key="LabelColorBrush"
Color="{DynamicResource DynamicColor}"/>
Add following 3 color brush dictionaries in some folder from your project...
<!-- Name = OrangeColorResource.xaml -->
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Color x:Key="DynamicColor">Orange</Color>
</ResourceDictionary>
<!-- Name = BlueColorResource.xaml -->
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Color x:Key="DynamicColor">Blue</Color>
</ResourceDictionary>
<!-- Name = RedColorResource.xaml -->
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Color x:Key="DynamicColor">Red</Color>
</ResourceDictionary>
Note that the key remains the same i.e. DynamicColor.
Now clear and recreate color dictionaries in App.Resources. I have done that in the code behind of Window.xaml.cs
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Application.Current.Resources.MergedDictionaries.Clear();
Application.Current.Resources.MergedDictionaries.Add(
new ResourceDictionary()
{
Source = new Uri("Resources\\"
+ ((ComboBox)sender).SelectedItem.ToString()
+ "ColorResource.xaml",
UriKind.RelativeOrAbsolute) });
}
Now as and when you select a color from the drop down, the dynamic color changes on the static resource brush. Note that there is no Style involved.
I hope this answers what you are asking.
By the way: the reason for this post had some more complex background. I really wanted to use a single resource dictionary whereby I could change colors, fonts, fontsizes, etc. dynamically during runtime (by an end-user). I am working on a tax form application. And the tax forms presented on screen for user input are resolving their resources at the Application level. So far so good.
But at the same time I want to present the user a print preview of the tax form where the same resourcedictionary (as object type, not as object instance) is used to define color schemes, fonts, fontsizes, etc. to be used for printing. Which can differ from the styling used for on screen user input. That's why I wanted to "attach" the resource dictionary on (for example) the FixedDocument level so that all pages in the document would refer to it. And when changing colors, fonts etc. all pages with common elements (TextBlocks, TextEditors, etc.) would respond to the change.
And then I became stuck...as described in this post.
For now I have a nice workaround by creating a specific instance of the resourcedictionary, storing it as a private variable and attach it to every individual page I put in the fixed document. It works and that already pleases me. But my programmers heart is still a little ached, because I would prefer to use a single instance of the resource dictionary and put it at some top level control so all controls in it can use it.
As a programmer we have to live with workarounds as well ;) If you have any further suggestions, I'm open to receive them. Thanx for your support thus far.
Greetz, Joep.
Also see: MSDN Forum Post about this issue

How can I apply a style to the Window Control in WPF?

I am setting a style for the Window in the App.xaml like such:
<Application x:Class="MusicRepo_Importer.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib" StartupUri="TestMaster.xaml">
<Application.Resources>
<Style TargetType="Window">
<Setter Property="WindowStyle" Value="None"></Setter>
</Style>
</Application.Resources>
</Application>
With which I basically want every Window to have its WindowStyle's property value set to None (to remove the default windows frame and border); But it is not working.
What am I missing here?
I believe you have to name the style and apply it to each window like the following..
In app.xaml/resources..
<Style x:Key="MyWindowStyle" TargetType="Window">
<Setter Property="WindowStyle" Value="None"></Setter>
</Style>
Then in the window.xaml..
<Window x:Class="MusicRepo_Importer.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MyStyledWindow" Style="{StaticResource MyWindowStyle}">
This should work, but simply applying the style with TargetType for Window in the resource won't force the Window to use that style although it seems to work for other elements.
Edit:
Found some info in relation to applying default styles to a window element..
If you supply a TargetType, all
instances of that type will have the
style applied. However derived types
will not... it seems. <Style
TargetType="{x:Type Window}"> will not
work for all your custom
derivations/windows. <Style
TargetType="{x:Type local:MyWindow}">
will apply to only MyWindow. So the
options are
Use a Keyed Style that you specify as
the Style property of every window you
want to apply the style. The designer
will show the styled window.
From the Question: How to set default WPF Window Style in app.xaml?
The person who answered the question had a interesting idea about inheriting from a base window that has the style applied.
I know this question is quite old but I will answer anyway.
Here is the code that works fine for me in C# 4.0.
It just duplicates style for all subclasses in the resource dictionary.
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
if (this.Resources.Contains(typeof(Window)))
{
var types = Assembly.GetEntryAssembly().GetTypes();
var subTypes = types.Where(x => x.IsSubclassOf(typeof(Window)));
Style elementStyle = (Style)this.Resources[typeof(Window)];
foreach (Type subType in subTypes)
{
if (!this.Resources.Contains(subType))
{
this.Resources.Add(subType, elementStyle);
}
}
}
base.OnStartup(e);
}
}
Now your style from App.xaml should work for all windows.
p.s. Yeah, I know this is not the cleanest or fastest way but it works. :)

Resources