Cannot find a Resource with the Name/Key - c#

I'm trying to unit test a user interface using the Silverlight 4 Toolkit.
When I attempt to instantiate the UserControl, it's throwing an exception because in the XAML of the UserControl it's using a Style defined App.xaml.
Is there a way to load the resource somehow before I instantiate the UserControl? Am I going about this the wrong way?
Here's the unit test code:
[TestMethod]
public void ExerciseTimePeriodUserInterface()
{
CustomUserControls.TimePeriodFilter timePeriodFilter = new CustomUserControls.TimePeriodFilter();
}
Here's the reference to the style in the UserControl:
<Border Style="{StaticResource FilterBorderWrapper}">
And lastly, here's the style defined in the App.xaml:
<Style TargetType="Border" x:Key="FilterBorderWrapper">
<Setter Property="Background" Value="#F1F5FB" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="#CBD9E9" />
<Setter Property="CornerRadius" Value="2" />
<Setter Property="Margin" Value="2" />
</Style>

If all your resources placed into ResorceDictionaries. You can simple create Application instance and add that Dictionary to the resources. Please look at the sample:
Application _app = new Application();
ResourceDictionary dictionary = new ResourceDictionary();
dictionary.Source = new Uri("pack://application:,,,/Gui.Mvvm;component/Themes/YourResourceDictionary.xaml");
_app.Resources.MergedDictionaries.Add(dictionary);
For my WPF app this works fine. After this code was written I was able to test my Template Selectors, DataTemplate Selectors and so forth. All code using in codebehind calls to
Application.Current.FindResource()
works quite good.

You can't easily unit test User controls out of context. Too many dependencies.
You can test your view models with unit tests (which should be where all your code is anyway) and the Silverlight controls with some form of GUI automation (or humans if you can't afford the latest GUI test tools).
As VC 74 implied, if you are not already using MVVM, you probably should (if you want to do Silverlight unit testing).

Rick,
basically, I was getting the same error. Later then, i simply copied the Resources and all definitions to the Test-Projects App.xaml file (I also have a Styles.xaml resource), and my UI Tests work without problems.
Of course, it's never the best solution to copy "anything", but hey, I really don't care about the styles. Plus, you could even define own styles for the UI Testing Panel.
HTH
Thomas

Related

WPF Default DynamicRessource values

Is there a way to save a default value for dynamic ressources in a custom control library?
I have created a custom control library and therefore I use a default Style which resides in the Generic.xaml file. This "default style" uses references to dynamic resource markers (see in the example).
<Style TargetType="{x:Type local:BorderlessWindow}">
<Setter Property="Foreground" Value="{DynamicResource ForegroundColor}" />
<Setter Property="Background" Value="{DynamicResource BackgroundColor}" />
<Setter Property="TitleBackground" Value="{DynamicResource AltBackgroundColor}" />
<Setter Property="Template" Value="{StaticResource DefaultBoderlessWindowTemplate}" />
</Style>
Everything is working as expected if I reference to my custom control library in a new project and add the dynamic resource markers in this new projects app.xaml but the values are empty if I do not do this.
So I want some kind of default values. In other words:
"Take the value of {DynamicResource ForegroundColor} or if this do not exist blue."
I thought I just have to add the default values in the Generic.xaml (MergedDictionary) but this wont do the job. Does anyone have a solution?
The only solution I can think about is to replace the dynamicResource markers with the concret (default) values (e.g. blue, green, black) and handle resources in the "consuming" app if you know what I mean.
After InitializeComponent you can see if the resource you need is found and add a default if not.
public MainWindow()
{
InitializeComponent();
try
{
var resource = FindResource("ForegroundColor");
}
catch (ResourceReferenceKeyNotFoundException)
{
Resources.Add("ForegroundColor", new SolidColorBrush(Colors.Red));
}
}
you are on a complex problem
see that
https://wangmo.wordpress.com/2007/09/27/themesgenericxaml/
Why is my style in Generic.xaml not working?
take care how you define your controldefault style
the place where you put themes\generic.xaml
where did you include your color scheme (normaly in generic)
check assemblyinfo
etc
if all is well structured, it must take your default color in the custom control assembly
or simply just include your generic from assembly in the app.xaml
<ResourceDictionary Source="pack://application:,,,/Client.Core;Component/themes/generic.xaml"/>

How do I dynamically change which Resource folder I get an image from?

I'm trying to implement 2 different themes for a WPF Application. I found this excellent post by #bendewey:
"Can WPF themes be used to include multiple skins for an application that can be changed at runtime?"
And have used it to implement two themes. I have created two Resource Folders, Lets call them ResourcesTheme1 and ResourcesTheme2 and Two Xaml Resource Dictionary files (Style1.xaml & Style2.xaml) that have the styles.
With this I have been able to set the following styles:
In Style1.xaml
<Style x:Key="HomeViewBackGroundImage" TargetType="Image">
<Setter Property="Source" Value="/ResourcesTheme1/Background.png" />
</Style>
In Style2.xaml
<Style x:Key="HomeViewBackGroundImage" TargetType="Image">
<Setter Property="Source" Value="/ResourcesTheme2/Background.png" />
</Style>
And this has worked a treat for me (if there's a better way please feel free to suggest it).
No the problem I have is that within my mainPage xaml I want to put on a row of buttons and each button has it's own image that it get's from binding to an ObservableCollection. I would like the Binding to look into the correct resource folder, but don't know how to make it happen without writing code behind.
So what I have is the following Binding:
<Image Name="ContentImage" Source="{Binding ImageName}" Stretch="UniformToFill">
And the following code behind:
if (useTheme1)
{
imageName = "/PlayingWithThemes;component/ResourcesTheme1/" + imageFileName;
}
else
{
imageName= "/PlayingWithThemes;component/ResourcesTheme2/" + imageFileName;
}
Any thoughts on how I could make the source for the image something like:
Source="ResourceFoler + {Binding ImageName}"
Or is there something more generic than:
/PlayingWithThemes;component/ResourcesTheme1/"
That I could use.
Thanks in advance.
A

The name ... does not exist in the namespace

This problem is pretty much the same as this one. However my problem is that I get this error but it does compile run and find it find.
My XAML with the error is a resource dictionary (in a different project) and it is trying to use an enum called MainViewMode in a style. I have inherited the code from a previous team so I do not know why it was originally written like this but the xaml consists of all the path data for icons (using the <geometry> tag) as well as all of the Styles. I don't think this is relevant to the problem but just thought I would highlight it anyway.
As I said, when the program runs it does work fine however the designer mode is not working on one of the forms I need to modify and it is making it really annoying.
xmlns:cenum="clr-namespace:ABC;assembly=DEF"
...
<Style x:Key="MainViewToggleButtonStyle" TargetType="ToggleButton">
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="OverridesDefaultStyle" Value="true" />
<Setter Property="CommandParameter" Value="{x:Static cenum:MainViewMode.Overview}" />
...
</style>
I have a resource dictionary, it calls an enum in a different project and says that it can't find it. It does however find it at runtime and work fine.
The main issue is that the designer doesn't load for any forms using this resource dictionary.
I believe your problem is that your namespace is incorrect. Take a look at the top answer in the question you linked to and notice how they have the example namespace. Since you're getting the enum from a different project you will also want to add that project as a reference.
To get the namespace right find the folder that the enum class is in, or if it's not in a folder just the project name. The namespace will be like one of the following,
If it's in a folder try something like this
ProjectName.FolderName;assembly=ProjectName
If not try something like this
ProjectName;assembly=ProjectName

Allowing Copy/Paste for XamDataGrid across application

I'm working on an application that had many infrgistics XamDataGrids. I'd like to at least provide Copy to clipboard abilities on them. This can easily be achieved in the XAML for each grid, with:
<igDP:XamDataGrid DataSource="{Binding}" >
<igDP:XamDataGrid.FieldLayoutSettings>
<igDP:FieldLayoutSettings AllowClipboardOperations="Copy"/>
</igDP:XamDataGrid.FieldLayoutSettings>
</igDP:XamDataGrid>
However, I would like all XamDataGrids in the application to allow this Copy to clipboard feature. I thought styling would be the answer, but for some reason, this does not work:
<Style TargetType="{x:Type igDP:FieldLayoutSettings}">
<Setter Property="AllowClipboardOperations" Value="Copy" />
</Style>
I've tried many variations on the above, but nothing seems to take, and there are no error messages. Any help would be really appreciated.
This is untested but perhaps you require the fully qualified name as below: (including the XamDataGrid.)
<Style TargetType="{x:Type igDP:XamDataGrid.FieldLayoutSettings}">
<Setter Property="AllowClipboardOperations" Value="Copy" />
</Style>
This question is old, but I just ran across it.
Anyway, the TargetType of your style will be XamDataGrid.
The property you are setting is FieldLayoutSettings.
<Style TargetType="{x:Type igDp:XamDataGrid}">
<Setter Property="FieldLayoutSettings">
<Setter.Value>
<igDp:FieldLayoutSettings AllowClipboardOperations="Copy"/>
</Setter.Value>
</Setter>
</Style>
Is this style defined in a place (like App.xaml) where every XamDataGrid can inherit it?
Have you tried defining this style in the same XAML file as a XamDataGrid that might use it? I would start by seeing if you could make this work as a local style in one specific place.

WPF Updating styles at runtime

I would like to update the default Window style dynamically at runtime so I can change the FontSize and FontFamily dynamically at runtime. I found that Styles in your resource dictionary are sealed at runtime and cannot be changed, so I used the following method of updating the style:
<Style TargetType="{x:Type Window}">
<Setter Property="FontFamily" Value="Arial"/>
<Setter Property="FontSize" Value="12pt"/>
</Style>
With the following code:
Style newStyle = (Make a copy of the old style but with the FontSize and FontFamily changed)
// Remove and re-add the style to the ResourceDictionary.
this.Resources.Remove(typeof(Window));
this.Resources.Add(typeof(Window), newStyle);
// The style does not update unless you set it on each window.
foreach (Window window in Application.Current.Windows)
{
window.Style = newStyle;
}
There are several problems with this approach and I have a few questions as to why things are the way they are.
Why are styles sealed at runtime and is there a way of making them unsealed?
When I re-add the new style, why is this not picked up by all of my windows? Why do I have to go and manually apply it to every window?
Is there a better way?
I would probably tackle this with a "settings service" which exposes properties for the various settings, and fires INPC as you would for normal binding. Next up I'd change that style to be something like:
<Style x:Key="MyWindowStyle">
<Setter Property="FontFamily" Value="{Binding Path=FontFamily, Source={StaticResource SettingsService}, FallbackValue=Arial}"/>
<Setter Property="FontSize" Value="{Binding Path=FontSize, Source={StaticResource SettingsService}, FallbackValue=12}"/>
</Style>
With your "settings service" defined as a static resource:
<services:SettingsService x:Key="SettingsService"/>
Then in each window make sure the style is set as a DynamicResource:
<Window Style="{DynamicResource MyWindowStyle}" .... >
There is often a lot of misunderstanding around the differences between Static and Dynamic resources, but the basic difference is Static is a "one time" setting whereas Dynamic will update the settings if the resource changes.
Now if you set those properties in your "settings service" they will fire INPC, which will update the Style, which the DynamicResource will pick up on and alter the Window properties accordingly.
Seems like a lot of work, but it gives you some nice flexibility, and all the "heavy lifting" is done purely using Bindings. We use a similar technique on a project I'm working on at the moment so when a user chooses a fill/stroke colour the various tools in the toolbar update to reflect the new values.

Categories