I have a custom collection defined in my window resources as follows (in a Sketchflow app so the window is actually a UserControl):
<UserControl.Resources> <ds:MyCollection x:Key="myKey" x:Name="myName" /> </UserControl.Resources>
I want to be able to refer to this collection in the codebehind, which I expected would be by the x:Name, but I can't seem to access it.
I can get a reference to it using
myRef = (MyCollection) this.FindName("myKey");
but this seems hackish. Is this bad practice, and what would be better? Thanks :)
To add a Resource Dictionary into your WPF application, right click the WPF project > add a Resource Dictionary. Now apply the resource "myAnotherBackgroundColor" to button background and observe the changes.
WPF supports different types of resources. These resources are primarily two types of resources: XAML resources and resource data files. Examples of XAML resources include brushes and styles. Resource data files are non-executable data files that an application needs.
StaticResource are retrieved only once by the referencing element and used for entire life of the resource. On the other hand, DynamicResource are acquired every time the referenced object is used.
Tip You can create a resource dictionary file in Microsoft Visual Studio by using the Add > New Item… > Resource Dictionary option from the Project menu. Here, you define a resource dictionary in a separate XAML file called Dictionary1. xaml.
You should use System.Windows.Controls.UserControl
's FindResource()
or TryFindResource()
methods.
Also, a good practice is to create a string constant which maps the name of your key in the resource dictionary (so that you can change it at only one place).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With