WPF icon preloading - c#

My application does a lot of work with currencies and so frequently makes use of 80-90 .ICO files I have as resources which are country flags, to represent each currency. Most screens use these and it seems a waste to keep reloading them for each use, especially given that when I use a datatemplate that has an IMG tag, it freezes the GUI or makes it very unperformant when loading these in ListViews etc.
Is there some way or design that's recommended in WPF whereby I can preload these images into the WPF application space so that whenever they are referenced, they are already cached and loaded globally so I only have to load them into memory once at application start, then every usage from then on in is lightning fast?
Thanks

I would suggest to place them into the Application.Resources in your xaml.
Those are loaded only once and accessible everywhere in your app.'
See How to: Use Application Resources on msdn.
EDIT:
In your class where you bind your items too (class that contains IconSelect) you need to add an extra property.
public BitmapImage BitmapIconSelect
{
get
{
return Application.Resources[IconSelect];
}
}
And then bind to this property:
<Image Source="{Binding BitmapIconSelect, IsAsync=True, Mode=OneWay}" Width="20" Height="20" />
I wrote this code freehand, so I am not sure if it compiles but I hope you get my point.

Related

How does WPF allow named items to be recognized across the entire application?

When a named XAML element is used in a WPF application, it can be accessed from anywhere. For example:
<Grid>
<Grid>
<TreeViewItem Name="itemScreen" />
The element itemScreen will be directly accessible in MainWindow(), although it is several levels deep in the XAML hierarchy.
How does WPF enable this to work in C#?
There's a mechanism called NameScope.
https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/wpf-xaml-namescopes
Simple markup you put in a window which has no templating or styling will all have the one namescope.
If you dig through that link it will explain about styles and templates in more detail. Essentially, they have their own namescope.
This is probably as far as you want to go with an explanation at this stage but there are a couple of oddities like when you "inherit" a style using basedon.
I wouldn't worry about them just yet but throw it to the back of your mind for later.
ps
That control is a private member of your window and the name doesn't have to be unique across the entire application.

Layouts with events and properties

How would I make an XAML layout which had bound properties and events? I'm going out of my mind.
First of all, it's for a chat application and a single room chat works fine, in the sense that I can design the layout of the application in XAML with name properties here there and everywhere in order to control it in C# but when it comes to repeating this layout multiple times because of multiple rooms, it becomes a bit of a problem. I was doing it solely by C# this lead to hundreds of lines of just defining controls and adding them to the window, and one problem with that would be the fact that name properties would collide.
I was going to go with modifying a ControlTemplate of a random control for example a Frame, but then I run into the issue of defining custom properties and events.
I just have no idea how I can do what I want to do. I've asked for help in many places to no avail.
I am honestly going out of my mind, and on the verge of giving up entirely.
My aim is to have a tabcontrol with multiple rooms, I need to be able to access controls in each room with ease so I can modify the content. I'm just getting no where.
Edit
Public chat template is obviously different to the private chat template, hence why I've failed so badly at this.
You can do it using MVVM pattern which is preferable when dealing with WPF.
However, this requires some experience and a lot of mind-warping.
Luckily, you can always use classic approach if you are coming from the Windows Forms world.
Just create an user control for the chat room which contains GUI, data, logic, event handlers, ...
Place instances of this chat room user control inside tab container and you are done.
Sounds like a perfect place for a data template!
First off, you need a "ChatRoom" class that contains all the state information for a given room. Then your main ViewModel needs to have a collection of these objects. Finally, set up your tab control with a DataTemplate that is probably nearly identical to your current window.
The TabControl would look like:
<TabControl ItemsSource="{Binding ActiveRooms}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
... (All your chat room stuff)
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
That way, whenever you create a new room (ActiveRooms should be an ObservableCollection, by the way) it automatically a new set of controls and binds them to the new room's instance properties.

MVVM Light - Multiple ViewModels (and connecting them up)

I am trying to learn the MVVM pattern (C#), having come from a Windows Forms background. I am using the MVVM Light toolkit, and so far I think it is brilliant.
I have made several small applications, however one thing I am struggling with is introducing a second view.
I want to (for example), have a button on my MainViewModel, which via a RelayCommand, opens up a new Window - let's say an "About" window. I have done hours of research on the web for this however it seems I can't get my AboutViewModel to communicate with/show my AboutView.
I have placed a receiving messenger in the code-behind constructor of the AboutView.xaml - however I can't get it to receive any messages from the AboutViewModel, and thus can't make it 'Show()'.
If anyone has an example of an Mvvm Light WPF app using multiple views that would be great :)
There are two ways I can think to do this easily
The first would be to use a Popup instead of a new Window. For example, I often put properties in my ViewModel for PopupContent and IsPopupVisible, and set those values anytime I want to display my Popup control. For example, a ShowAboutPopup relay command might run something like this:
void ShowAboutPopup()
{
PopupContent = new AboutViewModel();
IsPopupVisible = true;
}
You can display it using a Popup object, or a custom UserControl. I prefer to use my own custom Popup UserControl, which will usually end up looking like this:
<Window>
<Canvas x:Name="RootPanel">
<SomePanel>
<!-- Regular content goes here -->
</SomePanel>
<local:PopupPanel Content="{Binding PopupContent}"
local:PopupPanel.IsPopupVisible="{Binding IsPopupVisible}"
local:PopupPanel.PopupParent="{Binding ElementName=RootPanel}" />
</Canvas>
</Window>
The PopupContent property is a ViewModel (such as an AboutViewModel), and DataTemplates are used to tell WPF to draw specific ViewModels with specific Views
<Window.Resources>
<DataTemplate DataType="{x:Type local:AboutViewModel}">
<local:AboutView />
</DataTemplate>
</Window.Resources>
The other method is to have some kind of ApplicationViewModel that runs on startup, and is responsible for the overall application state, which includes which window(s) are open.
Typically I prefer to have a single ApplicationView that contains a ContentControl to display the current page
<Window>
<ContentControl Content="{Binding CurrentViewModel}" />
</Window>
however it can also be used to manage multiple windows. If you do use it to manage multiple Window objects, be warned that this will not be a pure ViewModel because it will need to access some View-specific objects, and referencing UI objects it not something a ViewModel should do. For example, it may subscribe to receive ShowWindow messages, and upon receiving those messages it would create the specified View and show it, and possibly hide the current window as well.
Personally, I try to avoid multiple windows as much as possible. My usual method is to have a single View that contains consistent application objects for any page, and a ContentControl containing dynamic content that changes. I have an example using this navigation style on my blog if you're interested
As i can see you want a navigation in your MVVM app?
Word goes to the creator of MVVM Light - Laurent Bugnion - with his post about using Navigation Service for switching Views. It's actually about Windows Phone & Silverlight but same should apply to WPF.
Also this answer in related question uses this approach.

Is there any way to use StaticResource in a WPF control library and be able to view at design-time?

I have a WPF Control Library that is being added to a windows forms application. We want to allow the controls to be localizable, however I am not sure how to FULLY accomplish this without duplicating code. This is what I am doing now.
Basically, in the windows forms app, before the main application kicks off, I am instantiating an App.xaml that live within the forms app (containing my links to my resources that also live within the forms app). This works perfectly for runtime.
However, my user controls all have Content="{StaticResource SomeVariableName}", which end up being blank. I can fix this by having an app.xaml and appropriate resource dictionaries in my control library that match those in my windows forms app. However, this is duplicated code.
Things I have already tried to no avail:
Instantiate the App.xaml that lives within the user control library from within my forms app. This does not work because the URIs to my resources is looking for an embedded resource, not my local resource dictionary (I could then simply copy the resource files from the control to an appropriate location within my forms app on build). Could I leverage DeferrableContent here? There is not much online as far as I could find on this attribute and how it should be used, though.
I would like to use post builds for both App and dictionaries, however, the App instantiation is a static reference to a compiled App.xaml as far as I can tell. So, App.xaml must live within the form at least
I did try to have a duplicated App.xaml with a post build moving the resourcedictionary.xaml. I figured that a duplicated app.xaml is ok since that is the driving force and you might not want to rely on one from the control anyway (which circles back and makes you wonder if you should then have the App.xaml in the control at all? Unless you want to allow a default that uses embedded resources....) That too failed saying it could not find the resource even though it was placed where the URI should have been pointing to. The decompiled code points to Uri resourceLocater = new Uri("/WindowsFormsApplication3;component/app.xaml", UriKind.Relative);
So, Is there any way to allow for this to work AND have design time viewing of the component defaults AND avoid duplication? Or, is the duplication OK in this case? If my 2nd bullet's sub-item seems ok (duplicated App.xaml with build copied resourcedictionaries), how do I make it not look for a component level item, but instead a file level one?
Last question (and I can post this separately if necessary) that I just paid attention to. My App.xaml is being built into the code, so that does not allow me to create new ResourceDictionaries on the fly anyway. Is there any way to do this?
Final option...possibly the best one?
- I plan on using Andre van Heerwaarde's code anyway, so should I just check for the existence of a file and add it as a merged resource on the fly? Basically, have one App.xaml in my user control that links to a default embedded ResourceDictionary. And, then have the code look for the appropriate localized resources on the fly, which can be relative file paths? The only downside I see here is that the default cannot be changed on the fly...which I could probably even have that look in a specified place (using some sort of convention) and have that preferred over the built-in one?
Oh, and my reason for not wanting embedded resources is so that end users can add/modify new localized resources after the build is deployed.
I can add code if it will help you visualize this better, just let me know.
UPDATE
I am now running into a further problem with styling and not just localizing.
Here is an example of one of the internal buttons on one of the controls:
<Button Style="{StaticResource GrayButton}"
Some more things I tried/thought:
I cannot create an app.xaml (that would never be used) with the ResourceDictionary set up as ApplicationDefinitions are not allowed in library projects. I could embed this in the control's resources, but then that would always take precedence over any application level resources and I lose customizability.
Here is a connect case that actually sounds like what I am looking for, however it does not provide any real solution to this
The solution (beyond the top..which does not work) that I can think of that might work (and have yet to try) also seems like a lot of work for something that I would think should be simple. But, I might be able to create some dependency properties in the control that I can Bind to and then allow those to be overriden by the project that will be using the control. As I said, that seems like a lot of work for a pretty simple request :). Would this even work? And more importantly, is there a better, simpler solution that I am missing?
I've run into this problem once, and I resolved it by dropping the whole "Resources are objects indexed by key in canonical dictionaries" thing.
I mean, the simple fact of defining a resource in one project and referencing it in another by it's "key" should give goosebumps to any sane person. I wanted strong references.
My solution to this problem was to create a custom tool that converts my resource xaml files to static classes with a property for each resource:
So MyResources.xaml:
<ResourceDictionary>
<SolidColorBrush x:Key="LightBrush" ... />
<SolidColorBrush x:Key="DarkBrush" ... />
</ResourceDictionary>
Becomes MyResources.xaml.cs
public static class MyResources {
static MyResources() {
// load the xaml file and assign values to static properties
}
public static SolidColorBrush LightBrush { get; set; }
public static SolidColorBrush DarkBrush { get; set; }
}
For referencing a resource, you can use the x:Static instead of StaticResource:
<Border
Fill="{x:Static MyResources.LightBrush}"
BorderBrush="{x:Static MyResources.DarkBrush}"
... />
Now you got strong references, autocompletion and compile time check of resources.
I too had a problem dealing with Styling Themes and available static resources. So, I created a stand-alone library that basically had nothing but the themes to be used all nested like your MERGED resources of your prior linked question.
Then, in the Windows form (.xaml), I just put reference to that library, something like
<Window x:Class="MyAppNamespace.MyView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ... />
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- Common base theme -->
<ResourceDictionary Source="pack://application:,,,/MyLibrary;component/Themes/MyMainThemeWrapper.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Rest of XAML for the WPF window>
</Window>
The "component" appears to refer to the root of the given "MyLibrary" project. In the actual project, I created a subfolder called "Themes", hence the source includes... ;component/Themes/...
The "MyMainThemeWrapper.xaml" is very much like your nested Merged Resource dictionaries, and it sees everything perfectly from other libraries.
Here's my partial solution to your problem. I haven't tried to handle loose resources, but I have some success with sharing resources between WinForms and WPF.
Create a class library to contain your resources in .ResX files (e.g. Resources.resx, Resources.fr.resx, etc)
Create your WPF controls in a WPF user control library
Create your WinForms host
Reference the resources in your resource library from WPF using the Infralution.Localization.Wpf markup extension and culture manager, e.g.
<TextBlock Text="{Resx ResxName=ResourceLib.Resources, Key=Test}"/>
Put the content of your WPF user controls into one or more resource dictionaries as control templates,e,g
<ControlTemplate x:Key="TestTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="{Resx ResxName=ResourceLib.Resources, Key=Test}"/>
</Grid>
</ControlTemplate>
Use the resource template in your user controls
<UserControl x:Class="WpfControls.UserControl1"
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" mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" >
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ResourceDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<ContentControl Template="{StaticResource TestTemplate}" />
</UserControl>
Add a couple of lines of code to make things work
public partial class UserControl1 : UserControl
{
// we require a reference to the resource library to ensure it's loaded into memory
private Class1 _class1 = new Class1();
public UserControl1()
{
// Use the CultureManager to switch to the current culture
CultureManager.UICulture = Thread.CurrentThread.CurrentCulture;
InitializeComponent();
}
}
Here's a simple demo app called WindowsFormsHost.7z

How do I correctly pass a UserControl that contains resources between two threads?

I have been trying to figure out this problem for a while now and am just stumped. I have created a UserControl type (edited below) that i am trying to generate and serialize from a background thread.
The background thread generating the Control is marked as STA and uses a memory stream to pass the control. However the control contains a data template in the UserControl.Resources section that is causing errors during deserialization.
Is it not possible to pass a user control containing a resource between threads without defining the resources in an external merged resource dictionary?
code:
UserControl:
<UserControl x:Class="WPF_Base.Example">
<UserControl.Resources>
<DataTemplate DataType={x:Type Example2}>
<Example2View />
</DataTemplate>
</UserControl.Resources>
<Grid>
<StackPanel>
<ItemsControl ItemSource="{Binding GetExamples}" />
</StackPanel>
</Grid>
</UserControl>
ThreadCode (Presented as a single thread):
System.IO.MemoryStream streamer = new System.IO.MemoryStream();
var testExample = new WPF_Base.Example();
var test = System.Windows.Markup.XamlWriter.Save(testExample);
var test2 = new System.IO.StringReader(test);
var test3 = System.Xml.XmlReader.Create(test2);
var test4 = (WPF_Base.TestExample)System.Windows.Markup.XamlReader.Load(test3); //Exception thrown here about key already existing in the dictionary
EDIT:
The controls are being generated and built in the other thread for due to the possibly that user may be loading a file that contains many pieces of data (controls are in a MVVM pattern) that each are represented as a view on the screen. During this process i would still want the UI to be responsive and not appear to "lock". I guess i could stagger when the controls are rendered to the screen instead of all at once since that would be the major bottle neck with the views.
EDIT:
If you are indeed using the MVVM pattern, you should create your control on the main (UI) thread, create your object data on the other thread, and set it as the control's DataContext when it is available. Better yet, don't create the control at all until each 'DataContext' becomes available. This is a common way to keep your application responsive even when you may have to wait a long time for the data, say over the internet.
OLD --> About the first part of your question:
This isn't a threading problem. In short, this is not working because when you try to deserialize the data, the runtime is trying to add the template, again, to the internal 'XAMLType' representation of your object. This effect is not limited to templates however, any resource that you define will cause a problem when you attempt to load it in this fashion. Even giving names, etc. to XAML elements in your control will cause problems.
EDIT:
The XAML serializer approach that you are trying to use is not what it is intended for. Additionally, you don't want to create controls on another thread for the reason that you mention in you comment.

Categories