Accessing a resource via codebehind in WPF

后端 未结 6 807
刺人心
刺人心 2020-12-01 07:06

I have a custom collection defined in my window resources as follows (in a Sketchflow app so the window is actually a UserControl):



        
相关标签:
6条回答
  • 2020-12-01 07:36

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

    0 讨论(0)
  • 2020-12-01 07:36

    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.

    0 讨论(0)
  • 2020-12-01 07:36

    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); ;
        }
    }
    
    0 讨论(0)
  • 2020-12-01 07:36

    I got the resources on C# (Desktop WPF W/ .NET Framework 4.8) using the code below

    {DefaultNamespace}.Properties.Resources.{ResourceName}
    
    0 讨论(0)
  • 2020-12-01 07:40

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

    0 讨论(0)
  • 2020-12-01 07:48

    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"];
    
    0 讨论(0)
提交回复
热议问题