Navigation Failed. Cannot Locate Resource for ModernTab WPF - c#

I am using ModernUI in my application. In the code below, I have a link "General" in ModernTab which is inside a window PriceSettingsView in a project PriceSettingsUI. When I run this application the PriceSettingsView window is shown and the link "General" is also working fine, but when I use PriceSettingsView in another project (calling from menu click event), the PriceSettingView window is showing up but the "General" link displays the following error message:
Navigation Failed. Cannot locate resource
Can someone please suggest why it is not working when calling the view from another project? Is something wrong with the source attribute when calling the view from another project?
<mui:ModernWindow x:Class="PriceSettingsUI.PriceSettingsView"
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:mui="http://firstfloorsoftware.com/ModernUI"
mc:Ignorable="d"
Style="{StaticResource EmptyWindow}" Title="PriceSettingsView" Height="700" Width="900">
<Border Margin="0,5,0,0" BorderBrush="{StaticResource Accent}" BorderThickness="1">
<mui:ModernTab>
<mui:ModernTab.Links>
<mui:Link DisplayName="General" Source="/Views/GeneralSettings.xaml"/>
</mui:ModernTab.Links>
</mui:ModernTab>
</Border>
</mui:ModernWindow>
Error Message:
Please let me if anyone needs additional information.

But, when I use "PriceSettingsView" in another project (calling from menu click event) PriceSettingView window is showing up but link "General" giving error message as "Navigation Failed. Cannot locate resource".
You provide a URI for GeneralSettings that is relative to the current project. In the original project A, the Views folder exists and contains the GeneralSettings view, but when you use PriceSettingsView in another project B, there neither the folder nor the view are present and therefore the view cannot be resolved.
You have to specify the URI to GeneralSettings relative to the assembly that contains it and reference the corresponding project. Specify the referenced assembly in the URI, for example:
<mui:Link DisplayName="General" Source="/PriceSettingsUI;component/Views/GeneralSettings.xaml"/>

Related

Image not visible in WPF 2015

I'm having some difficulty getting an image to display in WPF, Visual Studio Community Edition 2015.
The first issue involves a lack of dialog in the "Source" property for the image. WPF Tutorials of VS show a way to browse for the file under the source property.This does not appear to be an option under VS 2015 Community edition. Is there any way to enable this feature? Or is it not enabled in the "Community" edition?
The second issue is, the image is not visible at run time, but visible in the designer. Previous posts suggest to enable the "Build Action" for this image to "Resource". There seems to be number of files to set the Build Action on: If I set the MainWindow.xaml file to BuildAction->Resource I get the following error:
Error CS0103 The name 'InitializeComponent' does not exist in the current context
.... If I try to set any other file to BuildAction->Resource I get the following error:
Markup file is not valid. Specify a source markup file with an .xaml extension.
.. And I seem unable to recover without deleting the solution and starting from scratch.
Here is the XAML code
<Window x:Class="WR.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Demo" Height="350" Width="300" >
<Grid>
<ListBox Name="DemoListBox" Margin="15">
<Image x:Name="Image1" Source="/resources/facebook.png">
</Image>
</ListBox>
</Grid>
Thanks in advance
BuildAction->Resource should be set for file facebook.png

Can't use InkCanvas in SilverLight

I am trying to create my first program in SilverLight. But I can't use the InkCanvas.
Simply, I just:
Create a new project.
Choose SilverLight Application (Framework 4.5)
UnCheck "Host the silverlight application in a website..."
SilverLight version 5
"WCF RIA Services" unchecked
Click on ToolBox > Choose Items > Select InkCanvas from SilverLight components
Add InkCanvas to the form & Change it's background color to black
Click on "Start" (Debug)
But I can't see or use the Canvas.
Here is the XAML:
<UserControl 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:Workspace="clr-namespace:Microsoft.Expression.Prototyping.Workspace;assembly=Microsoft.Expression.Prototyping.Runtime"
x:Class="SilverlightApplication3.MainPage"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid x:Name="LayoutRoot"
Background="White">
<Workspace:InkCanvas HorizontalAlignment="Left"
Height="204"
Margin="36,52,0,0"
VerticalAlignment="Top"
Width="310"
Background="Black" />
</Grid>
</UserControl>
Then I get these 2 errors:
Error 1 Undefined CLR namespace. The 'clr-namespace' URI refers to a
namespace 'Microsoft.Expression.Prototyping.Workspace' that could not
be found. c:\users\xperator\documents\visual studio
2012\Projects\SilverlightApplication3\SilverlightApplication3\MainPage.xaml 6 21 SilverlightApplication3
and
Error 2 The type 'Workspace:InkCanvas' was not found. Verify that you
are not missing an assembly reference and that all referenced
assemblies have been built. c:\users\xperator\documents\visual studio
2012\Projects\SilverlightApplication3\SilverlightApplication3\MainPage.xaml 12 10 SilverlightApplication3
As the error says, there is no Workspace in the Prototyping namespace. I can see in the Solution explorer, there is only 2 References related to the InkCanvas:
Microsoft.Expression.Prototyping.Interactivity
microsoft.expression.prototyping.runtime
Tried to add the "Workspace" from the "Add Reference" but couldn't find it.
UPDATE :
I think actually the InkCanvas is not official ported to silverlight yet. Tried to do the same steps on a fresh pc, and I just noticed InkCanvas wasn't there in the first place. Maybe something related to Blend added the prototype control in my own PC. Still it doesn't work :(
I am open to any suggestion for alternatives to InkCanvas.

'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.'

The exception in the title is thrown when I open a window in WPF, the strange thing is that this does not happen on my Windows 7 development machine nor does it happen when it is deployed on Windows 7.
I only get this error on Windows XP, and only the second time that I open the window.
Here is the code to open the window:
ReportParametersWindow win = null;
bool canOverWrite = _shownReports.Contains(rpt.FriendlyName);
if (!(canOverWrite))
win = new ReportParametersWindow(rpt.FriendlyName, rpt.ReportParameters, canOverWrite);
else
win = new ReportParametersWindow(rpt.FriendlyName, (container.ParametersWindow as ReportParametersWindow).Controls, canOverWrite);
win.ShowDialog();
And the XAML for the window:
<Window xmlns:my="clr-namespace:MHA.Modules.Core.Controls;assembly=MHA.Modules.Core"
x:Class="MHA.Modules.Reports.Views.ReportParametersWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Parameters" Height="500" Width="600" MinWidth="500" MaxHeight="500"
Icon="/MHA.Modules.Reports;component/Images/Parameters.ico" SizeToContent="WidthAndHeight"
WindowStartupLocation="CenterScreen"
xmlns:odc="clr-namespace:Odyssey.Controls;assembly=Odyssey" Closed="Window_Closed">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="0" Name="ScrollViewer1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" CanContentScroll="True">
<StackPanel Name="ParameterStack">
<my:LocationCtl Text="Parameters for report - " Name="loc"/>
</StackPanel>
</ScrollViewer>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<CheckBox ToolTip="This will replace the first report of the same type that was shown." Name="chkOverwrite" Content="Overwrite old" VerticalAlignment="Center" Margin="5,0"></CheckBox>
<Button Grid.Column="2" HorizontalAlignment="Right" Margin="5,0" Height="30" Style="{StaticResource DionysusButton}" Width="100" IsDefault="True" Click="Button_Click">
<StackPanel Orientation="Horizontal">
<Image Source="/MHA.Modules.Reports;component/Images/Success.png"></Image>
<TextBlock Margin="5,0" Text="Accept" VerticalAlignment="Center"></TextBlock>
</StackPanel>
</Button>
</Grid>
</Grid>
Does anyone have suggestions?
The solution is quite a weird one but I have it figured out.
I realized that the error was occurring on the InitializeComponent() of the window, I then added a try catch to the constructor and showed the InnerException of the Exception.
The error that I received is "Image format not recognized".
I have no idea why this happens only on XP and the second time that the window is shown but by replacing my .ico with a .png the problem was resolved.
Hope this helps someone.
I just ran into this issue as well... I know this is old, but what I had to end up doing was set the images to Resource, and Copy Always... only by browsing my /bin/Debug folder did I realize that the images were not at a valid path location
This problem can also occur if the required image is not available at the specified location. So Check the inner exception and add any image that might have been missed or misspelled.
I got this error because my Command Binding of a Button was wrong:
<Button Command="MyCommand" />
instead of
<Button Command="{Binding MyCommand}" />
You Should first Import Image to your project
Solution Explorer - Show All
then Right Click on the image and select Include
Now Use
end
In my case the root cause was wrong BuildAction property on all images. I fixed it by changing BuildAction from Content to Resource.
I got this exception after moving my Resource Dictionary from root of my application to a subdirectory. In my case the problem were Image paths inside my Style setters inside the dictionary. After I preceded them with a forward slash '/', the application started to work again. If you're having a similar problem, open the resource dictionary, and the error will be highlighted with the blue 'squiggly' line.
In my case, I have added 'WpfToolkit' refrence to my module, and there is no need.
After deleting this reference, everything was ok. Strange!
Just go to Project>[Your Project Name] Settings and set your .ico file as icon now your .ico file is mentioned in your manifest file and you can simply include your .ico file in your XAML file using
Icon="[icon file name].ico"
<Window x:Class="[Your project's name].MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="" Height="500" Width="720"
Icon="[your icon's name].ico">
In my case, I found the mew added icon(image) file is not added into my project. It is resolved after I added these new image files into my project, not just file copy.
In my case the files existed on disk but were not referenced in the project. I added them to the project but the error persisted despite reloading the solution and restarting Visual Studio.
I changed the references to an existing file that was already in the project and it ran fine (albeit with the wrong graphic). I then changed it back to the original reference and it ran fine again but with the correct image. Presumably the error was getting cached somehow until it was flushed out of the system...
Remove the "WPFToolkit" reference from your cs.proj file.
<Reference Include="WPFToolkit, Version=3.5.40128.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
It should do the trick.
copy and paste the file name is changed. that's why I get this error.
well, in my case I added the new photos to the image Folder in FileExplore while image folder was added to the project while ago. and there wasn't any problem with the image path in the project. but when I build the project I face to the same error.
then I add those new photos to project by right click on the image folder and add the existing item and selected new photos. then I cleaned the solution and build it again.
There are many ways to cause this issue. Since the exception isn't specific. Here is a list of solutions to try from this thread.
Firstly, you can try/catch the InitializeComponent() call which is throwing the exception to get more details about what happened.
If the image is an icon (.ico) file use an image (.png) or equivalent instead
In some cases .ico files are problematic - I was using .NETCore
Make sure your image file has a build action of Resource or Embedded Resource
The resource files described in this section are different than the
resource files described in XAML Resources and different than the embedded
or linked resources described in Manage Application Resources (.NET). - MSDN
Ensure your reference to the file is spelled and pathed correctly
Example: "/Resources/logo.png" if you have a folder at the project level
Notice the prefix /.
Colors codes in the xaml file missing the hashtag prefix "#000FE0"
In my case, another program was using the image and somehow was blocking the access.
I mad a copy and this worked.
<Window
.....
Height="450" Width="400"
Icon="../Resources/SettingsCopy.png" >
To improve upon user2125523:
If you've added the image to the project and checked and double checked that the file spelling is correct, try renaming the image to mirror a different existing image. Build/run, then put your image file name back and build/run again.
For example:
My original code kept throwing the OP error on LargeImage="/img/32/delete.order.png" even though this file exists.
<telerik:RadRibbonButton Text="Object Properties" Size="Large"
Name="PropertiesButton" IsTabStop="True"
telerik:ScreenTip.Description="Get object properties"
Click="PropertiesButton_Click"
LargeImage="/img/32/properties.png"
SmallImage="/img/16/properties.png" />
<telerik:RadRibbonButton Text="Reset Tab Order" Size="Large"
Name="ClearTabOrderButton" IsTabStop="True"
telerik:ScreenTip.Description="Reset tab order of all fields"
Click="ClearTabOrder_Click"
LargeImage="/img/32/delete.order.png"
SmallImage="/img/16/delete.order.png" />
So, I changed LargeImage="/img/32/delete.order.png" to LargeImage="/img/32/properties.png", ran the program, and changed it back to "/img/32/delete.order.png". Finally the error was gone.
FYI VS2012.3 Win8.1Preview
I had the same issue and to add an image to you solution you have to do it through the wizzard. In the solution explorer -> right click on the appropriate folder-> add existing Item -> and then browse to your image. That worked for me. Hope this helps.
Thanks for you answers.
Try to set Build Action of Property of Image file as Resource.
Exception used to occur within constructor. Button's command binding was incorrect.
Eg: <Button Command="MyCommand" />--> Wrong
<Button Command="{Binding MyCommand}" />--> Right
In my case, I got this error when I had
<Border Background="eeeeee">
instead of
<Border Background="#eeeeee">
(notice the missign #)
I found "UpdateSourceTrigger=Pr" somewhere in my XAML.
Must have happened during editing.
Compiling went OK, no error then whatsoever.
Setting a BreakPoint in Application_DispatcherUnhandledException in app.xaml.cs revealed the error.
Corrected to "UpdateSourceTrigger=PropertyChanged" and the world was at it should have been.
I work on Win 10 Pro, VS2017
I encountered this error and figured out that the Image Source path format has a mistake. a forward slash / was added as follows:
Source="/TestProject;component/Images//hat_and_book.png
I removed that extra slash and the error had gone.
I got the same error message, then I find this solution :
Image not displaying at runtime C# WPF
Find your folder:Go to properties of the added image, set Build Action =>as Resource and Copy To Output Directory =>as Copy if newer.
In My case I have wrote a border tag with height property then i had to remove the value leaving the property like this
<Border Background="{StaticResource MainBackgroundBrush}" BorderThickness="1" Height="">
</Border>
The Compiler gave me the same error but the IDE have no problem so after some hard search i have found it. so make sure every property is properly set. I hope this would be useful for anyone.
it is caused by Non-standard tag option in xaml to find it set
InitializeComponent();
Function in - try mode - like this
try {
InitializeComponent();
}
catch (Exception ex) {
MessageBox.Show(ex.Message.ToString());
}
now MessageBox(( show line number with incorrect setting in control .axml file.(it just show first incorrect line tag error after Corrected it then run app again and see next one)

Adding x:Name to a user control gives error in generated code of page its used in

I am basically using a user control for the first time, so hopefully it's just a dumb mistake.
I have a simple user control
<UserControl x:Class="TestProject.WebApp.myUserControl"
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"
mc:Ignorable="d"
xmlns:riaControls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.DomainServices"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
<Grid>
<sdk:AutoCompleteBox Name="myACB" ItemsSource="{Binding Data}" FilterMode="StartsWith" MinimumPrefixLength="2" >
</sdk:AutoCompleteBox>
</Grid>
</UserControl>
I am using the control in another page (in a stack panel):
<navigation:Page x:Class="TestProject.WebApp.myPageView"
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"
mc:Ignorable="d"
xmlns:local="clr-namespace:TestProject.WebApp"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation">
<Grid>
<StackPanel Orientation="Horizontal">
<local:myUserControl x:Name="myUC" />
</StackPanel>
</Grid>
</navigation:Page>
The control is in the same namespace as page. Removing the x:Name allows the project to compile and the control functionally works. When x:Name is specified I get an error in the generated code of the page:
Type 'TestProject.WebApp.myUserControl' is not defined.
It happens on these lines of code:
internal TestProject.WebApp.myUserControl myUC;
this.myUC == (TestProject.WebApp.myUserControl)this.FindName("myUC")
I tried with two different controls. Same thing. The generated code has "using TestProject.WebApp;" so I don't know why there is an error only when I have a named instance of the control.
I also cannot seem to use just the Name property. I even tried overloading the NameProperty in the control.
I was able to find a post about this here:
.g.vb file claims that Type X is not defined, even though it is!
Apparently, there is an issue when a project has a service reference (in my case I am using RIA services) and the user control resides in an assembly with the same root namespace as the one you are trying to use it in.
So for me it was,
TestProject.WebApp
Then I tried creating a new project for just the control
TestProject.Controls
Same problem.
Then, when I renamed the project and changed the namespace to
CustomControls
it worked.
Hopefully this saves someone else from some frustration and I really hope this problem can be fixed by MS soon.
What you are showing here should work. What is the default namespace in your project property's? Also did you rename your user control after you created it. Both of those issues could be causing you problems.

Silverlight defaultStyle problem

I have the following scenario:
Create a new class library project called Lib1
1.1. Add a new control called control1, Themes/generic.xaml file and specify
the default style of control1.
Create a new class library project called lib2.
2.1.Add a new control called control2, Themes/generic.xaml file and specify
the default style of control2. In the dafaultStyle of control2 I use control1.
My question is: Do I have to copy/paste the defaultStyle xaml of control1 into the
generic.xaml of lib2, to use control1 with its style applied in control2?
The default style lookup for a Control is always done in the assembly that the Control is defined in. So if Control1 is defined in Lib1.dll, the default style will always be looked for in generic.xaml in Lib1.dll. It doesn't matter where the Control is being used from.
Just to make sure I understand your answer correctly, I will restate it in my own words:
You want to have a Silverlight class
library (Lib1) that houses a control
(Control1).
You want to have a
Silverlight class library (Lib2)
that houses a control (Control2).
You want to have the control use their respective generic.xaml files for respective control styles.
Control2 is to include Control1 in its style definition, without redefining its style in the generic.xaml file from Lib2.
If this is correct, I will describe my answer below:
Yes, this is possible as Keith Mahoney said here. I will go into detail on his answer and an example.
Each Silverlight class library generates a Dynamic-link library (dll) when compiled. All the classes (controls) and resources (styles) are contained in these dll's. Thus, when you create a lib1 class library with a style resource for a control contained within, it will all be stored in the lib1 dll.
Below is my example of the solution:
Setting up the solution:
First, I created new solution (StackOverflow Example.sln). Then I added a new project to the solution of type Silverlight Class Library (Lib1 1.1). Please note that Silverlight does not always play nicely with spaces in the namespace, so you may want to (as I did) rename the namespace to Lib1. See "How-To's" section for details on how to do this. Next I added the second project to the solution of type Silverlight Class Library (Lib2 2.1). I again, changed the root namespace of this project to one without spaces. Finally, I added a Silverlight Application project to my solution (SLApplication). Please note that in adding the Silverlight application project, you will be prompted to add a web project or web page to your project for creating the Silverlight control. Either option will work, please use the best for your situation. I used the separate website option (default). Now, when we setup the two class libraries, we were given a default starter class1.vb file. Let's rename these file to Control1.vb (for Lib1 1.1) and Control2.vb (for Lib2 2.1) in the solution explorer. When we do this, Visual Studio 2008 asks us if we'd like it to rename the class to match this new name, Click 'Yes'. Next up, let's figure out how to setup the themes for each of our controls.
Setting up themes:
I will start with the first control library (Lib1 1.1). First, create a new folder under the root of the project; name it "Themes" (case doesn't matter). Under this folder, add a new item of type xml and name it generic.xaml. For help on how to do this, see the "How-To's" section. Open the generic.xaml file, if it isn't already open. Delete the xml declaration text that was automatically inserted for you, and use the following for your initial definition:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- Styles go here. -->
</ResourceDictionary>
Now, since our Control1 control lives in this class library, we will need to add an xml namespace declaration (xmlns) (http://en.wikipedia.org/wiki/XML_namespace -sorry about the non link, my rep needs to be higher.) to our generic.xaml file. To do this, add the following line: xmlns:lib1="clr-namespace:Lib1" before the grater than symbol (>) in the top declaration. Once this is done, we can layout a simple style. Please note that we're setting the default background color to "Red" in order to differentiate the two controls. Please see below for the simple style for Control1:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lib1="clr-namespace:Lib1">
<!-- Style for Control1 -->
<Style TargetType="lib1:Control1">
<Setter Property="Background" Value="Red" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="lib1:Control1">
<Grid x:Name="LayoutGrid" Background="{TemplateBinding Background}">
<TextBlock Text="Control 1" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
With this let's start with the Control2. This will be very similar to the previous declaration for Lib1 1.1. If you haven't already done so, please add the Themes folder and the generic.xaml file as you did for the first library (Lib1 1.1). Now, for this project, you will need a reference to the Lib1 1.1 project. If you need help doing this, please see the "How To's" section. Once this is referenced, open the generic.xaml file, if it isn't already open. The definition of this file is almost identical; however, we will also be referencing the other projects namespace as well. See below:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lib2="clr-namespace:Lib2"
xmlns:lib1="clr-namespace:Lib1;assembly=Lib1">
<!-- Styles go here. -->
</ResourceDictionary>
Notice that now we are not only referencing our own namespace (lib2) but also referencing the other control's namespace (lib1) in the xml namespace declaration. Also notice that in the non-local control library, we also must reference the assembly name. Since we want to use the control (and its style) from lib one, we will need a place to use it in this project. For this, I have setup a grid with separate rows for each control. Please note that we're setting the default background color to "Blue" in order to differentiate the two controls. Please see below for Control2's definition:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lib2="clr-namespace:Lib2"
xmlns:lib1="clr-namespace:Lib1;assembly=Lib1">
<!-- Style for Control2 -->
<Style TargetType="lib2:Control2">
<Setter Property="Background" Value="Blue" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="lib2:Control2">
<Grid x:Name="LayoutGrid">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<lib1:Control1 Grid.Row="0" />
<Grid x:Name="Control2" Grid.Row="1" Background="{TemplateBinding Background}">
<TextBlock Text="{TemplateBinding Text}" />
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
This just sets up the fact that we want to have styles. We now need to tell Silverlight that we want these styles to be applied to our controls.
Using themes:
In our classes, we have to tell Silverlight that these are going to be custom user controls, to do this, we need to inherit from Control (or any other UIElement control - for this example, we will stay simple, and use Control). In order to tell the control to use a style defined in the generic.xaml, we need to do this in our constructor of each control.
For Control1:
Public Sub New()
MyBase.DefaultStyleKey = GetType(Control1)
End Sub
For Control2:
Public Sub New()
MyBase.DefaultStyleKey = GetType(Control2)
End Sub
Now all we have to do now, is tell our web site to use our new control(Control2).
Setting up the WebApplication:
You will need to reference both class libraries from your web project. See "How-To's" section for details on how to do this. Open up the Page.xaml file in your web application project (SLApplication). Your default should look something like this:
<UserControl x:Class="SLApplication.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
</Grid>
</UserControl>
We will add to this the xml namespace declaration for our Silverlight class library (Lib2 2.1) so that we may reference Control2. Now that we have referenced our class library, we can use any controls that are declared within. If you try to use the namespace without building after you add it to your xmlns declaration, you may not see any declared classes (controls) within. To fix this, build once. Please also note, that Visual Studio 2008 is sometimes weird about custom libraries, and may generate an error that says the custom library is not defined. This is fixed with a re-launch of the solution (Close Visual Studio and reopen). The final code to show the Control2 (which contains Control1) is as follows:
<UserControl x:Class="SLApplication.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lib2="clr-namespace:Lib2;assembly=Lib2"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<lib2:Control2 />
</Grid>
</UserControl>
Now build, and run. If everything went well, you should see the following:
Screen Shot http://www.imagefrog.net/out.php/i40631_StackOverflowExample.jpg
The full project can be downloaded from Google Code:
http://code.google.com/p/stackoverflow-answers-by-scott/wiki/1366075
Zipped source:
http://stackoverflow-answers-by-scott.googlecode.com/files/1366075.zip
Enjoy!
How-To's:
Change project namespace
In the solution explorer expand the project on which you want to change the namespace, and double click on the "My Project". For Silverlight class library projects, you will have four tabs on the left, one of which is "Silverlight". Select this tab, if it is not already selected. Under the "Root namespace" textbox, change the namespace to your desired namespace.
Add 'generic.xaml' to project
In the solution explorer, right click on the project name. Click "Add", and then click "New Folder". This will create a folder under the root of the project. Name this folder "themes". Please note that case does not matter here. Right click on the "themes" folder, click "Add", then click "New Item...". A dialog box appears for you to select what item type you want to add. Click "XML File" under the Templates section. Change the name to generic.xaml under the name field (at the bottom of the dialog). Click Add.
Create a project reference
To create a project reference, right click on the project that needs the reference. Select "Add Reference..." from the menu. A dialog box will be displayed for you to choose the reference to add. Select the "Projects" tab at the top of this dialog. Select the desired project reference. If you do not see the project that you want to reference in this list, check that you have added the project to the solution.

Categories

Resources