Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

How can I access ResourceDictionary in wpf from C# code?

I have a DataTemplate defined in a xaml file that I want to access via C# code. Can anyone please tell me how can I access it? I added a new ResourceDictionary file and its name is Dictionary1.xaml. I have a data template such as:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DataTemplate x:Key="mytemplate">
        <TextBlock Text="Name:" Background="Blue"/>
    </DataTemplate>
</ResourceDictionary>

not I have a ListBox called listBox1 and I want to assign it to it's Itemtemplate property but I'm not getting how can i do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since Application.Current was null in my case, I've ended up using this:

    var myResourceDictionary = new ResourceDictionary();
    myResourceDictionary.Source =
        new Uri("/DllName;component/Resources/MyResourceDictionary.xaml",
                UriKind.RelativeOrAbsolute);  

and then getting the specified key I needed by using myResourceDictionary["KeyName"] as TypeOfItem

(source)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...