Import separate XAML as ResourceDictionary and assign x:Key

后端 未结 2 1041
孤城傲影
孤城傲影 2021-01-02 21:54

I downloaded the Visual Studio Image Library and I see that the included icons are available in vector format in the form of .XAML files. Here is an example:

2条回答
  •  滥情空心
    2021-01-02 22:20

    Is it possible to use this icon.xaml file without modifying the .xaml file itself?

    I don't believe so. While XAML looks a lot like XML, and follows a lot of XML rules, the XAML compiler doesn't seem to allow the DOCTYPE and ENTITY markup that would normally be used to import XML from one file into another. When used, the first error reported reads "DTD is prohibited in this XML document". Without the ability to provide a DTD, you can't declare entities, and thus won't be able to import the standalone XAML.


    If you want to use the generated XAML file directly, you can add the file to your project as a Resource. The resource data can then be loaded using XamlReader.Load() in code-behind, added at the appropriate time where you want it.

    For example, assuming you have copied the XAML file to a folder named "Resources" in your project, and set the "Build Action" for the file to "Resource", you can write code like this to retrieve the object:

    using (Stream stream = App.GetResourceStream(
        new Uri("pack://application:,,,/Resources/Add_16x.xaml")).Stream)
    {
        object o = XamlReader.Load(stream);
    }
    

    That will get a Stream object representing the XAML file data that has been embedded in your application and then load the WPF object the XAML represents, using the XamlReader.Load() method.


    Personally, when I am using these files, I just copy/paste the DrawingGroup element from the XAML file, into my own resource XAML file. The wrapper (Viewbox, Rectangle, and DrawingBrush) are all redundant anyway. What I really need is the DrawingGroup object.

    When I do this, I also remove the explicit syntax, and just include the children of the DrawingGroup directly, making the XAML a bit more concise. E.g.:

    
      
        
        
        
      
    
    

    You can then use the above resource however you like. For example, an idiomatic approach in WPF would be to declare a DataTemplate configured to display a Drawing the way you want, and then bind a given Drawing resource as the content for a content control. E.g.:

    
      
        
          
        
      
    
    

    Then elsewhere:

    (Making sure the style for the content control, e.g. your Button, is otherwise compatible with your Drawing resource, i.e. correct size, etc.)

提交回复
热议问题