通过WPF中的代码访问资源

时间:2010-01-22 14:30:10

标签: c# wpf xaml resources code-behind

我在我的窗口资源中定义了一个自定义集合,如下所示(在Sketchflow应用程序中,因此窗口实际上是一个UserControl):

<UserControl.Resources>
    <ds:MyCollection x:Key="myKey" x:Name="myName" />
</UserControl.Resources>

我希望能够在代码隐藏中引用这个集合,我希望它可以通过x:Name,但我似乎无法访问它。

我可以使用

获取对它的引用
myRef = (MyCollection) this.FindName("myKey");

但这看起来很乱。这是不好的做法,还有什么会更好?谢谢:))

6 个答案:

答案 0 :(得分:66)

您应该使用System.Windows.Controls.UserControl的{​​{1}}或FindResource()方法。

另外,一个好的做法是创建一个字符串常量,在资源字典中映射键的名称(这样你就可以只在一个地方更改它)。

答案 1 :(得分:23)

您也可以使用this.Resources["mykey"]。我想这并不比你自己的建议好多了。

答案 2 :(得分:15)

不完全直接的答案,但强烈相关:

如果资源位于不同的文件中 - 例如ResourceDictionary.xaml

您只需向其添加x:Class

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

然后在后面的代码中使用它:

var res = new Namespace.NewClassName();
var col = res["myKey"];

答案 3 :(得分:3)

您可以使用如下资源键:

<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); ;
    }
}

答案 4 :(得分:3)

如果您要访问其他类的资源(例如,不是隐藏在xaml代码后面的资源),则可以使用

Application.Current.Resources["resourceName"];

来自System.Windows命名空间。

答案 5 :(得分:0)

我使用下面的代码在C#(Desktop WPF W.NET Framework 4.8)上获得了资源

{DefaultNamespace}.Properties.Resources.{ResourceName}