Not able to access StaticResource in Xamarin Forms from app.xaml - xaml

I am not able to access static resources that created in app.xaml.
its my app.xaml code
<Application.Resources>
<ResourceDictionary>
<Color x:Key="AppDefaultColor">#07bab7</Color>
<Color x:Key="PageDefaultColor">#f0f0f0</Color>
</ResourceDictionary>
</Application.Resources>
when i try to use this in my page as static resource it gives error.
its my page code which i used to access static resource from app.xaml
<Label Text="Test" TextColor="{StaticResource AppDefaultColor}" />

Please Check that your app.xaml.cs class call InitializeComponent() method. In the App constructor which is required when creating the App.xaml and associated code behind.
Please look into picture

Related

How do I create constants to be used in Xamarin.Forms XML

As an Android developer I'm used to work with #dimen/-constants in Androids XML. I find this future useful because it allows me to easily change multiple places that should have the same pixel-length together.
Does Xamarin.Forms have a similar features that I can use?
Well what you looking for are ResourceDictionaries
XAML resources are definitions of objects that can be shared and re-used throughout a Xamarin.Forms application.
These resource objects are stored in a resource dictionary.
A ResourceDictionary is a repository for resources that are used by a Xamarin.Forms application. Typical resources that are stored in a ResourceDictionary include styles, control templates, data templates, colours, and converters.
In XAML, resources that are stored in a ResourceDictionary can then be retrieved and applied to elements by using the StaticResource markup extension. In C#, resources can also be defined in a ResourceDictionary and then retrieved and applied to elements by using a string-based indexer. However, there's little advantage to using a ResourceDictionary in C#, as shared objects can simply be stored as fields or properties, and accessed directly without having to first retrieve them from a dictionary.
Creating and Consuming a ResourceDictionary
Resources are defined in a ResourceDictionary that is then set to one of the following Resources properties:
The Resources property of any class that derives from Application.
The Resources property of any class that derives from VisualElement
A Xamarin.Forms program contains only one class that derives from Application but often makes use of many classes that derive from VisualElement, including pages, layouts, and controls. Any of these objects can have its Resources property set to a ResourceDictionary. Choosing where to put a particular ResourceDictionary impact where the resources can be used:
Resources in a ResourceDictionary that is attached to a view such as Button or Label can only be applied to that particular object, so this is not very useful.
Resources in a ResourceDictionary attached to a layout such as StackLayout or Grid can be applied to the layout and all the children of that layout.
Resources in a ResourceDictionary defined at the page level can be applied to the page and to all its children.
Resources in a ResourceDictionary defined at the application level can be applied throughout the application.
The following XAML shows resources defined in an application level ResourceDictionary in the App.xaml file created as part of the standard Xamarin.Forms program:
<Application ...>
<Application.Resources>
<ResourceDictionary>
<Color x:Key="PageBackgroundColor">Yellow</Color>
<Color x:Key="HeadingTextColor">Black</Color>
<Color x:Key="NormalTextColor">Blue</Color>
<Style x:Key="LabelPageHeadingStyle" TargetType="Label">
<Setter Property="FontAttributes" Value="Bold" />
<Setter Property="HorizontalOptions" Value="Center" />
<Setter Property="TextColor" Value="{StaticResource HeadingTextColor}" />
</Style>
</ResourceDictionary>
</Application.Resources>
Beginning in Xamarin.Forms 3.0, the explicit ResourceDictionary tags are not required. The ResourceDictionary object is created automatically, and you can insert the resources directly between the Resources property-element tags:
<Application ...>
<Application.Resources>
<Color x:Key="PageBackgroundColor">Yellow</Color>
<Color x:Key="HeadingTextColor">Black</Color>
<Color x:Key="NormalTextColor">Blue</Color>
<Style x:Key="LabelPageHeadingStyle" TargetType="Label">
<Setter Property="FontAttributes" Value="Bold" />
<Setter Property="HorizontalOptions" Value="Center" />
<Setter Property="TextColor" Value="{StaticResource HeadingTextColor}" />
</Style>
</Application.Resources>
Each resource has a key that is specified using the x:Key attribute, which becomes it dictionary key in the ResourceDictionary. The key is used to retrieve a resource from the ResourceDictionary by the StaticResource markup extension, as demonstrated in the following XAML code example that shows additional resources defined within the StackLayout:
<StackLayout Margin="0,20,0,0">
<StackLayout.Resources>
<ResourceDictionary>
<Style x:Key="LabelNormalStyle" TargetType="Label">
<Setter Property="TextColor" Value="{StaticResource NormalTextColor}" />
</Style>
<Style x:Key="MediumBoldText" TargetType="Button">
<Setter Property="FontSize" Value="Medium" />
<Setter Property="FontAttributes" Value="Bold" />
</Style>
</ResourceDictionary>
</StackLayout.Resources>
<Label Text="ResourceDictionary Demo" Style="{StaticResource LabelPageHeadingStyle}" />
<Label Text="This app demonstrates consuming resources that have been defined in resource dictionaries."
Margin="10,20,10,0"
Style="{StaticResource LabelNormalStyle}" />
<Button Text="Navigate"
Clicked="OnNavigateButtonClicked"
TextColor="{StaticResource NormalTextColor}"
Margin="0,20,0,0"
HorizontalOptions="Center"
Style="{StaticResource MediumBoldText}" />
</StackLayout>
For more detailed information kindly take a look here
Apart from the StaticResource as mentioned above, 2 other ways to do it.
First one is, Having static class for constants and refer them in the XAML.
public static class GlobalSetting
{
public static double ImageRotation { get { return 180; } }
}
In the Xaml, you need to add this namespace in the page directive,
xmlns:gb="clr-namespace:XXXX.StaticData"
and use the constant in the xaml code as below,
<Image Source="icon_back.png" Rotation="{x:Static gb:GlobalSetting.BackImageRotation}" HeightRequest="24" </Image>
Second approach is, having a constant parameter in the BaseViewModel, and binding them in the Xaml code.
Sounds to me like you want to define constants/styles in a ResourceDictionary:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/resource-dictionaries.
In the ResourceDictionary you can define your constants/styles by key, in your XAML you can then refer to them as follows:
Color={StaticResource MyColorFromDictionary}

Override theme resource in the scope of a Page

I want to override a theme resource, specifically the SystemAccentColor, in the scope of a specific page.
I have successfully done it in application wide scope. But I can't do it for a specific page.
XAML in App.xaml (this works fine)
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
<Color x:Key="SystemAccentColor">#862E2D</Color>
<SolidColorBrush x:Key="SystemControlHighlightAccentBrush" Color="Black"/>
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
</ResourceDictionary>
</Application.Resources>
XAML in Page.xaml (this doesn't work)
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
<Color x:Key="SystemAccentColor">#111111</Color>
<SolidColorBrush x:Key="SystemControlHighlightAccentBrush" Color="Black"/>
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
</ResourceDictionary>
</Page.Resources>
<!-- Control to test that the resource is overriden. The `ProgressBar` uses the accent color by default -->
<ProgressBar
Height="10"
Grid.ColumnSpan="3"
VerticalAlignment="Top"
IsIndeterminate="True" />
I don't know why the resource is not overridden in the scope of the page.
I have tried removing the override from App.xaml and only overriding the resources in Page.xaml but that doesn't work either.
However if I do this
XAML in Page.xaml
<ProgressBar
Height="10"
Grid.ColumnSpan="3"
VerticalAlignment="Top"
IsIndeterminate="True"
Foreground="{StaticResource SystemControlHighlightAccentBrush}"/>
Then the ProgressBar gets the correct foreground value. Which means that the ovverride does take place.
Does anybody know why this is happening? Or how I can override a theme resource for a specific page?
The best way is using Visual Studio or 'Blend for Visual Studio'. I'm using Visual Studio
Right click on the Element you want to edit (in your case, Progress bar) > select 'Edit Template' > 'Edit a Copy'
A 'Create Style Resource' shows up, Enter a name for your style & in the 'Define in' section, select 'This Document' (this ensures the style only applies to the page/window and not app wide) and click okay
Immediately, the Progress Bar includes a style attribute (see last image) using the new style you created. You can go ahead and modify the code snippet inserted by the IDE to suite your imagination.
I hope this helps out.

Overriding Resources from Generic.xaml in UWP Applications

This is my Generic.xaml where I define default background color for my control (CustomControlBackground):
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TomShane.Framework.Controls">
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
<SolidColorBrush x:Key="CustomControlBackground" Color="Gray"/>
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
<Style TargetType="local:CustomControl">
<Setter Property="Background" Value="{ThemeResource CustomControlBackground}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomControl">
<Border
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
In App.xaml I want to override the default background from Generic.xaml:
<Application
x:Class="TomShane.Framework.Demo.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TomShane.Framework.Demo"
xmlns:ctrl="using:TomShane.Framework.Controls"
RequestedTheme="Dark">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
<SolidColorBrush x:Key="CustomControlBackground" Color="Red"/>
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
With this technique I am able to override UWP system resources (like SystemControlBackgroundBaseLowBrush), but when I try to override the CustomControlBackground, the control's background stays always gray.
What is the thing I am missing?
The logic is wrong.
We can only override upper scope ResourceDictionary in lower scope ResourceDictionary. Actually, it's about the resource lookup behavior but not about which xaml file is loaded first
In WinRT xaml app, the Resource Dictionary scope looks like the following(not MS official picture):
Based on above, we can override system default resource in app.xaml, we can override system/application resource in page.xaml, and etc.
So in your code, actually, the resource defined in generic.xaml will override the resource you defined in app.xaml. If we simply remove the resource CustomControlBackground from the generic.xaml, you will get the red background.
[update]
If you do want to have a default theme, you can keep the design, but we cannot use the x:Default for the resourcedictionary.
For example, if the requestedtheme is Dark(in your case). You can simply use the following to override the default one in app.xaml.
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Dark">
<SolidColorBrush x:Key="CustomControlBackground" Color="Yellow"/>
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
Or you can only put the theme into a separate file and reference it only in the client app's app.xaml. But you have to rewrite the file to use different values.
Its unfortunate that there isn't a good way to define theme resources for custom controls in such a way that they can be overridden in the same way that the built-in resources, like SystemControlBackgroundBaseLowBrush, can be. But there is a workaround if you're willing to move things around at runtime. The trick is to end up with a situation where your default resources are not contained in Generic.xaml, but are instead defined in a resource dictionary that is merged with the application's resources, where they CAN be overridden. There's more than one way to accomplish this.
One approach would be to create a separate resource dictionary that has an x:Class with an associated code file. Define your default theme resources in it. Then figure out a way to merge an instance of the class into the application's resources at runtime. One way would be in the static constructor of your control. Be careful not to merge more than one instance.
A somewhat different approach, which I like better, is to use code-behind of the resource dictionary in which you define the control's default style. But you can't have code-behind for Generic.xaml, because the framework will never instantiate an instance of the class. Instead, move the style into its own resource dictionary (with x:Class and code-behind) and add an instance of the new dictionary to the merged dictionaries of Generic.xaml. You will be able to move things around in the constructor of this resource dictionary, after the call to InitializeComponent. For example, if in the xaml file you define a resource dictionary in the MergedDictionaries collection and place your theme resources in in it, then at runtime you would be able to remove that dictionary from the MergedDictionaries collection and merge it into the application's resources.
A limitation of either approach is if you want to override resources by theme, i.e. Light and Dark. Placing an overriding resource directly into the resources of App.xaml will work, but will not allow different values for different themes. To achieve this, it is necessary to define the overriding resources inside the ThemeResources of a resource dictionary which itself is placed in the application resource's MergedDictionaries. (I don't know but it kind of seems like this might be a bug.)
CustomControl.xaml:
<ResourceDictionary x:Class="CustomControlLibrary.Themes.CustomControlTheme"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CustomControlLibrary">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Light">
<SolidColorBrush x:Key="CustomControlBackground" Color="#000000" />
</ResourceDictionary>
<ResourceDictionary x:Key="Dark">
<SolidColorBrush x:Key="CustomControlBackground" Color="#FFFFFF" />
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
<Style TargetType="local:CustomControl">
<Setter Property="Background" Value="{ThemeResource CustomControlBackground}" />
</Style>
</ResourceDictionary>
CustomControl.xaml.cs:
namespace CustomControlLibrary.Themes
{
partial class CustomControlTheme
{
public CustomControlTheme()
{
InitializeComponent();
if(MergedDictionaries.Count > 0)
{
var themeResources = MergedDictionaries[0];
MergedDictionaries.RemoveAt(0);
Application.Current.Resources.MergedDictionaries.Insert(0, themeResources);
}
}
}
}
Generic.xaml:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:themes="using:CustomControlLibrary.Themes">
<ResourceDictionary.MergedDictionaries>
<themes:CustomControlTheme />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

How to use style in another resources?

I have a based style that target type is button call BaseButtonStyle in ResourceDictionaries/CustomControlStyles/BaseButtonStyle.xaml.
And I create a new button style that extended from BaseButtonStyle call AddButtonStyle.
Both styles I have added in App.xaml as followings.
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!--Buttons-->
<ResourceDictionary Source="ResourceDictionaries/CustomControlStyles/BaseButtonStyle.xaml" />
<ResourceDictionary Source="ResourceDictionaries/CustomControlStyles/AddButtonStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Then I add a button that refer to AddButtonStyle but it raised an error
Cannot find a Resource with the Name/Key BaseButtonStyle
What's wong with my reference?
Try to use an absolute path:
"ms-appx:///ResourceDictionaries/CustomControlStyles/BaseButtonStyle.xaml"
Of course I don't know if that path fit your file location.

DataTemplate not found in merged ResourceDictionary

I'm currently developing a universal app for Windows Phone 8.1 and Windows 8.1.
I share most of my code, but I'm willing to keep style resources appart.
Some context : First, right now I've only started the WP8.1 projects so everything is related to this platform. In this WP8.1 project, I have a MainPage.xaml which contains a Pivot control. One of the PivotItem is a UserControl called, for clarity purposes, MyUserControl.
I created a resource dictionary Styles.xaml into my "Assets" directory, in BOTH platform projects. Then, I registered those 2 new files into my shared App.xaml like this :
<Application.Resources>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
<ResourceDictionary x:Key="ResourceDictionary">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Assets/Styles.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
In the WP8.1 project Styles.xaml file, I created a DataTemplate :
<DataTemplate x:Key="MyDataTemplate">
<TextBlock Text="This is a textblock" />
</DataTemplate>
In MyUserControl, I've added a ListView and bound it on the ItemTemplate property to MyDataTemplate like this :
<ListView ItemTemplate="{StaticResource MyDataTemplate}" ItemsSource="{Binding MyContent}" />
When I run the solution and I end up with this error :
Cannot find a Resource with the Name/Key "MyDataTemplate"
Does anyone know why I encounter this error ? What did I do wrong ?
An odd thing : when I right click > "Go To Definition" on the MyDataTemplate bound in the ListView.ItemTemplate property, it routes me to the right place.
Thank you in advance for your help !
Your code is wrong, here is the correct one
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Assets/Styles.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
</ResourceDictionary>
</Application.Resources>