Accessing a resource via codebehind in WPF

2019-01-14 05:14发布

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 :)

5条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-14 05:31

You may also use this.Resources["mykey"]. I guess that is not much better than your own suggestion.

查看更多
Bombasti
3楼-- · 2019-01-14 05:33

You can use a resource key like this:

<UserControl.Resources>
    <SolidColorBrush x:Key="{x:Static local:Foo.MyKey}">Blue</SolidColorBrush>
</UserControl.Resources>
<Grid Background="{StaticResource {x:Static local:Foo.MyKey}}" />

public partial class Foo : UserControl
{
    public Foo()
    {
        InitializeComponent();
        var brush = (SolidColorBrush)FindResource(MyKey);
    }

    public static ResourceKey MyKey { get; } = CreateResourceKey();

    private static ComponentResourceKey CreateResourceKey([CallerMemberName] string caller = null)
    {
        return new ComponentResourceKey(typeof(Foo), caller); ;
    }
}
查看更多
Bombasti
4楼-- · 2019-01-14 05:34

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).

查看更多
萌系小妹纸
5楼-- · 2019-01-14 05:35

Not exactly direct answer, but strongly related:

In case the resources are in a different file - for example ResourceDictionary.xaml

You can simply add x:Class to it:

<ResourceDictionary x:Class="Namespace.NewClassName"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <ds:MyCollection x:Key="myKey" x:Name="myName" />
</ResourceDictionary>

And then use it in code behind:

var res = new Namespace.NewClassName();
var col = res["myKey"];
查看更多
Rolldiameter
6楼-- · 2019-01-14 05:50

If you want to access a resource from some other class (i.g. not a xaml codebehind), you can use

Application.Current.Resources["resourceName"];

from System.Windows namespace.

查看更多
登录 后发表回答