Only last icon in XAML shown when icon used from resources - wpf

when I try to use a material design icon from the icon pack that is defined in the ResourceDictionary, only the first icon in XAML is rendered at run time. I've followed an example that can be found here.
Example follows:
App.xaml:
<Application x:Class="TestWpf.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestWpf"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<materialDesign:BundledTheme BaseTheme="Light" PrimaryColor="DeepPurple" SecondaryColor="Lime" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
<ResourceDictionary Source="pack://application:,,,/TestWpf;component/Dictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
Dictionary1.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes">
<materialDesign:PackIcon x:Key="CashIcon" Kind="Cash" />
</ResourceDictionary>
MainWindow.xaml:
<Window x:Class="TestWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<Button Content="{DynamicResource CashIcon}" />
<Button Content="{DynamicResource CashIcon}" />
<Button Content="{DynamicResource CashIcon}" />
</StackPanel>
</Window>
And the result is a window that looks like this:
In xaml editor all buttons have icons on them, as expected:
Why is this happening and, more important, how to fix this?
P.S. We've found out that if you create two Cash icons in the ResourceDictionary and apply each to a button, then they will both be shown but again, only once, you can't have say 3 buttons and 2 icons in ResourceDictionary.

one more solution is to use a non-shared resource (x:Shared Microsoft docs)
<materialDesign:PackIcon x:Key="CashIcon" Kind="Cash" x:Shared="False"/>
x:Shared Attribute: When set to false, modifies WPF resource-retrieval behavior so that requests for the attributed resource create a new instance for each request instead of sharing the same instance for all requests.
A scenario for x:Shared="false" is if you define a FrameworkElement or FrameworkContentElement derived class as a resource and then you introduce the element resource into a content model. x:Shared="false" enables an element resource to be introduced multiple times in the same collection (such as a UIElementCollection). Without x:Shared="false" this is invalid because the collection enforces uniqueness of its contents. However, the x:Shared="false" behavior creates another identical instance of the resource instead of returning the same instance.

The PackIcon type is a Control. An element in the visual tree in WPF can only have a single parent. In other words, the pack icon is still a single instance added as child of the first button, then moved to the second, then to the third. You will in fact have to create multiple instances of the pack icon.
Instead of creating resources, you could use the PackIcon markup extension.
<StackPanel>
<Button Content="{materialDesign:PackIcon Cash}"/>
<Button Content="{materialDesign:PackIcon Cash}"/>
<Button Content="{materialDesign:PackIcon Cash}"/>
</StackPanel>
Depending on your actual scenario, you could alternatively create a DataTemplate, which will automatically create instances of the pack icons for each button.
<DataTemplate x:Key="CashPackIconTemplate">
<materialDesign:PackIcon Kind="Cash" />
</DataTemplate>
<StackPanel>
<Button ContentTemplate="{StaticResource CashPackIconTemplate}"/>
<Button ContentTemplate="{StaticResource CashPackIconTemplate}"/>
<Button ContentTemplate="{StaticResource CashPackIconTemplate}"/>
</StackPanel>

Related

Why do resource files "disappear" from the WPF Designer when referenced from a Window?

Stackoverflow has other similar questions, but they seem to be related to usage in multiple assemblies or with the formatting of ResourceDictionary Source values. This question relates to single assemblies and the tests listed at the end demonstrate the Source value works as-is.
The following describes a small test application that illustrates the issue.
The test application has a style XAML file (MyStyle.xaml):
<ResourceDictionary
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<SolidColorBrush x:Key="FontColorKey" Color="DarkBlue" />
</ResourceDictionary>
Which is used in a UserControl (PanelChoice.xaml):
<ToggleButton
x:Class="PanelNS.PanelChoice"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="30" Width="100" Background="Orange"
>
<ToggleButton.Resources>
<ResourceDictionary >
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Styles/MyStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="FontColorKey" Color="Yellow" />
</ResourceDictionary>
</ToggleButton.Resources>
<TextBlock
Foreground="{StaticResource FontColorKey}"
Background="Pink" Text="Testing"
/>
</ToggleButton>
Which, in turn, is used on a test Window (MainWindow.xaml):
<Window x:Class="IncludeStyleTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PanelNS"
Title="MainWindow" Height="200" Width="200"
>
<Grid Background="Green">
<local:PanelChoice />
</Grid>
</Window>
Tests to isolate this issue:
This code compiles and when run displays green, orange and pink rectangles with yellow text in the middle (as expected).
Viewing PanelChoice.xaml in the XAML Designer shows orange and pink rectangles with yellow text in the middle (as expected).
However, viewing MainWindow.xaml in the designer shows Cannot create an instance of "PanelChoice" and lists Cannot locate resource 'styles/mystyle.xaml'. in the Visual Studio Error List pane.
If the <ResourceDictionary Source="/Styles/MyStyle.xaml"/> line in PanelChoice.xaml is removed (or commented out) and the project rebuilt, then viewing MainWindow.xaml in the designer shows green, orange and pink rectangles with yellow text in the middle and no error messages. It behaves as #1 when run.
To verify that MyStyle.xaml is properly referenced one can remove the <SolidColorBrush x:Key="FontColorKey" Color="Yellow" /> line in PanelChoice.xaml instead of removing MyStyle.xaml. This case behaves just as #1, but the text is dark blue instead of yellow. This demonstrates that MyStyle.xaml is properly referenced and is accessible.
NOTE: Visual Studio 2015 and 2017 both exhibit this behavior.
Take out the leading / in the .xaml reference so that it looks like this instead:
<ResourceDictionary Source="Styles/MyStyle.xaml"/>
The control is then able to be displayed properly in the Window when in the designer.
Another way to get it to show properly is to use the full physical path (you wouldn't do it this way, but just demonstrating the behaviour) e.g.:
<ResourceDictionary Source="\Users\colin.smith\Documents\visual studio 2017\Projects\WpfApp15\WpfApp15\Styles\MyStyle.xaml"/>
Yey another way that works:
<ResourceDictionary Source="/WpfApp15;component/Styles/MyStyle.xaml"/>
If you use the property picker to select the Source for your ResourceDictionary it does not put a leading / at the start of the Source when referring to the MyStyle.xaml that is in your Styles folder.
The issue seems to be with the designer. When it's providing a design surface which has to "include" another control which you have created in "the same" project, it must be doing something wrong when referring to those ResourceDictionaries with leading / paths.
Another way to get it to work...
If you move/create your "controls" in a separate "User Control" or "Custom Control" library, then you will be using a "pack" reference to refer to the resources...and the Window will be able to display that control properly in the designer.
I'm sure you can find an example of creating user controls in their own library...but will quickly show what it would kinda look like.
<ToggleButton
x:Class="WpfControlLibrary1
.PanelChoice"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="30" Width="100" Background="Orange"
>
<ToggleButton.Resources>
<ResourceDictionary >
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/WpfControlLibrary1;component/Styles/MyStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="FontColorKey" Color="Yellow" />
</ResourceDictionary>
</ToggleButton.Resources>
<TextBlock
Foreground="{StaticResource FontColorKey}"
Background="Pink" Text="Testing"
/>
</ToggleButton>
Then add reference to your WpfControlLibrary1 library, and use:
<Window x:Class="WpfApp15.MainWindow"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp15"
xmlns:controls="clr-namespace:WpfControlLibrary1;assembly=WpfControlLibrary1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid Background="Green">
<controls:PanelChoice />
</Grid>
</Window>

How to Define Common Resources Across WPF Applications (including templates)?

I am looking for a way to define a WPF resource (for now, to be used as a static resource) that is accessible from everywhere within my application.
My resource is defined in this resource dictionary:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="flatButtonStyle" BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" TargetType="{x:Type Button}">
<Setter Property="BorderThickness" Value="4"/>
</Style>
</ResourceDictionary>
The selected answer to this question indicates that I must merge that resource dictionary into my App.xaml file (of a project called AppWideResources):
<Application x:Class="AppWideResources.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/AppWideResources;component/CommonResources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
At first, this seems to work; the button in this window is appropriately styled in a flat way with an extra-thick border:
<Window x:Class="AppWideResources.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AppWideResources" Height="300" Width="300"
>
<StackPanel>
<Button Style="{StaticResource flatButtonStyle}" Content="Test" HorizontalAlignment="Stretch"/>
</StackPanel>
</Window>
However, this stops working as soon as I use my shared resource in a control template:
My (extremely simplified, for the purpose of this question) control:
using System;
using System.Windows;
using System.Windows.Controls;
namespace AppWideResources
{
public class MyControl : Control
{
static MyControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
}
}
}
... and the corresponding Themes\Generic.xaml file:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:AppWideResources">
<Style TargetType="local:MyControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyControl">
<StackPanel Orientation="Horizontal">
<Button Style="{StaticResource flatButtonStyle}" Content="1"/>
<Button Style="{StaticResource flatButtonStyle}" Content="2"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
This control is then inserted into my window:
<Window x:Class="AppWideResources.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:AppWideResources"
Title="AppWideResources" Height="300" Width="300"
>
<StackPanel>
<Button Style="{StaticResource flatButtonStyle}" Content="Test" HorizontalAlignment="Stretch"/>
<local:MyControl/>
</StackPanel>
</Window>
If I run this, a XamlParseException is thrown, saying that the static resource flatButtonStyle cannot be found.
The only workaround I have found is by explicitly merging the common resource dictionary into the local resource dictionary of the control template:
<ControlTemplate TargetType="local:MyControl">
<ControlTemplate.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/AppWideResources;component/CommonResources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</ControlTemplate.Resources>
<StackPanel Orientation="Horizontal">
<Button Style="{StaticResource flatButtonStyle}" Content="1"/>
<Button Style="{StaticResource flatButtonStyle}" Content="2"/>
</StackPanel>
</ControlTemplate>
However, not only is this quite verbose and error-prone with several lines of redundant code (my actual project contains quite a few templated controls, not just one), I am also concerned about wasting system resources by loading the static resources several times (once for every time CommonResources.xaml is included). (Is that concern justified? Or does WPF use the same instances every time when loading a particular resource dictionary?)
So, the question is: What is the proper way to make a WPF resource accessible throughout the whole application, including control templates?
StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. So, static resource has to be available at the time of loading.
It works for normal button since resource look up continues till application resources and resolve it from there. But MyControl template still not loaded into app visual tree so it can't traverse upto application resources.
There are two ways to achieve that:
Merge ResourceDictionary in Generic.xaml as well which you have already achieved.
Other way is to use DynamicResource which assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime.
Read it here - StaticResource v/s DynamicResource.
This will work without merging dictionaries in Generic.xaml:
<Button Style="{DynamicResource flatButtonStyle}" Content="1"/>
<Button Style="{DynamicResource flatButtonStyle}" Content="2"/>

WPF Controls as StaticResource in Resource Dictionary, used in multiple WPF Windows?

I have a Button control as a resource in Resource Dictionary as below:
<!--ButtonResources.xaml file-->
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Button x:Key="buttonResource" Content={Binding BoundText}/>
</ResourceDictionary>
<!--ButtonResources.xaml file-->
I now use this above button control bound to Content property of ContentControl controls in 2 different Windows .xaml files where each Window has its own DataContext and thus each window should display the Content of above button control based on its ViewModel's BoundText property value as below for each Window.
<Window x:Class="TestClass1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ButtonResources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<ContentControl Content={StaticResource buttonResource}/>
</Grid>
</Window>
But, the problem is that both Window's display same value for the BoundText property which means that both the WPF Windows have same instance of button control from resource, used in both the Windows.
How can I resolve this problem such that each Window gets a separate button control from the resource and still display different values for the BoundText property from their own ViewModel?
Edit:
For the reason mentioned in MSDN as below, I can't use x:Shared="False" attribute to resolve this:
•The ResourceDictionary that contains the items must not be nested
within another ResourceDictionary. For example, you cannot use
x:Shared for items in a ResourceDictionary that is within a Style that
is already a ResourceDictionary item.
Did you try to use the x:Shared attribute?
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Button x:Shared="False" x:Key="buttonResource" Content={Binding BoundText}/>
</ResourceDictionary>
For more info read here.
In case this does not work, you can store a template in your resource, instead of the button and use a ContentControl inside your window to display it.
Try:<Style TargetType="Button" x:Key="buttonResource">
<Setter Property="Content" Value="{Binding BoundText}" />
</Style>
<Button Style="{StaticResource buttonResource}" />

Accessing resources during initialization of control

lets assume we have the following control definition
<ctrl:ChildWindow x:Class="Control.Editor"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctrl="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
xmlns:local="clr-namespace:Control"
Width="400" Height="300"
local:AttachedProperties.DialogResult="{Binding Path=DialogResult}"
Title="{Binding Path=Caption}" Style="{StaticResource Title}" DataContext="{Binding}" HasCloseButton="False">
<ctrl:ChildWindow.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Control;component/Resources/BaseAppearance.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</ctrl:ChildWindow.Resources>
</ctrl:ChildWindow&gt
The problem is that the style on the root control cannot be set because the ResourceDictionary is not loaded.
How can I get access to the StaticResource Title during the initialization of the control, when I don't have access to the App class? I'm also not sure that it would be possible, if I would have access to it.
Regards
I'd recommend accessing your resource and doing the work in the .Loaded() event of your control.
Edit: On second thought... I think I know what you're doing now... You have a resource set in your App.xaml class, but you want to access it in your control.
Easy way around the problem is to set it to a DynamicResource instead... but this is less performant.
What is the BuildAction set to on your App.xaml in the property's tab?
If it is ApplicationDefinition... then you should be able to access your resource as you currently are.
I found the common way without using code behind. I knew it is possible. ^^
<ctrl:ChildWindow x:Class="Control.Editor"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctrl="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
xmlns:local="clr-namespace:Control"
Width="400" Height="300"
local:AttachedProperties.DialogResult="{Binding Path=DialogResult}"
Title="{Binding Path=Caption}" DataContext="{Binding}" HasCloseButton="False">
<ctrl:ChildWindow.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Control;component/Resources/BaseAppearance.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</ctrl:ChildWindow.Resources>
<crtl:ChildWindow.Style>
<StaticResource ResourceKey="Title" />
</crtl:ChildWindow.Style>
</ctrl:ChildWindow&gt

How to set tooltip for user control (from style file)

I created my control which looks like that
<UserControl BorderBrush="#A9C2DE" HorizontalAlignment="Left" x:Class="WPFDiagramDesignerControl.Components.UcWBSBlock"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="86" Width="151" >
<UserControl.Resources>
<ResourceDictionary Source="Tooltip.xaml"/>
</UserControl.Resources>
<Grid x:Name="MainGrid">
<TextBox Name="txtBox" Style="{StaticResource DefaultStyle}" >
</TextBox>
</Grid>
I also have a file with style for tooltip "Tooltip.xaml"
How can I use this style for entire UserControl?
Usually I did this with that code
<TextBox ToolTip="{StaticResource tooltipname}"/>
But it was easy because file with style was in resource dictionary of control where I placed textbox. However I can't do sth like that
<UserControl BorderBrush="#A9C2DE" HorizontalAlignment="Left" ToolTip="{StaticResource tooltipname"}/>
Because at this point my style isn't in resource dicionary yet.
I was trying to use this syntax
<UserControl.ToolTip> </UserControl.ToolTip>
but I don't konow how should I refer to static resource
Maybe it is lame question but I just don't konow how to do it :)
One option is to just use DynamicResource instead of StaticResource to defer the lookup until runtime and then use the attribute syntax:
<UserControl ... ToolTip="{DynamicResource tooltipname}" ...
You can also write the StaticResourceExtension using element syntax so that you can write it after the Resources section:
<UserControl.Resources>
<ResourceDictionary Source="Tooltip.xaml"/>
</UserControl.Resources>
<UserControl.ToolTip>
<StaticResourceExtension ResourceKey="tooltipname"/>
</UserControl.ToolTip>

Resources