Monday, September 7, 2015

WPF/XAML: Specifying a Namespace in a Referenced Assembly

In the previous post it was shown how to create a class library that contained a publicly accessible resource file: Visual Studio: Making a Resource File (resx) Public Versus Internal (default), The premise of the previous post was to share a class library (assembly) containing resources with multiple projects. In order for a WPF page to make use of the resources from another assembly, the page's XAML file must contain a reference to the namespace of the assembly containing resource file.

The solution used in the previous blog posting is as follows where the below screenshot is from Visual Studio 2015's Solution Explorer:



The WPF application's MainWindow.xaml page is as follows:

<Window x:Class="EpicWPFApplication.MainWindow"
  xmlns=
      "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc=
    "http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:local="clr-namespace:EpicWPFApplication"
  xmlns:epicclasslib=
    "clr-namespace:EpicClassLibrary;assembly=EpicClassLibrary"
  mc:Ignorable="d"
  Title="MainWindow" Height="350" Width="525">
  <Grid Height="319" VerticalAlignment="Bottom">

    <TextBlock Text="{x:Static epicclasslib:ResourcesThatWouldBeSwellToShare.MotherlyAdvice}" 
                   HorizontalAlignment="Center" 
                   VerticalAlignment="Center"/>

  </Grid>
</Window>

In the previous code snippet the top line in bold face (shown below) specifies EpicClassLibrary assembly and the EpicClassLibrary assembly:

xmlns:epicclasslib=
  "clr-namespace:EpicClassLibrary;assembly=EpicClassLibrary"

A TextBox control in the application XAML makes use of a text resource exposed by EpicClassLibrary:

    <TextBlock Text="{x:Static epicclasslib:ResourcesThatWouldBeSwellToShare.MotherlyAdvice}" 
                   HorizontalAlignment="Center" 
                   VerticalAlignment="Center"/>

When run the WPF applications, it displays the following:


No comments :

Post a Comment