XAML Forms not recognizing local and referenced classes - c#

I opened a VS 2012 Solution in VS 2015 and cannot get it to compile. It was originally targeting .Net 3.5 and used the WPF Toolkit, which caused some ambiguous references. I resolved that by removing the reference to the WPF Toolkit and replacing it with the package DotNetProjects.Wpf.Toolkit.
Now I have to tackle the next issue, which I suspect is not caused by the obvious but is a cascade from some other hidden gotcha from upgrading the versions.
My XAML forms are not recognizing the existence of classes within referenced namespaces. I can get them to come up on intellisense but the application won't compile and the error says something like: "The name "MainWindow" does not exist in the namespace "clr-namespace:FieldSheetPrinter".
I have defined my main form with the following:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:FieldSheetPrinter"
mc:Ignorable="d"
xmlns:Custom="http://schemas.microsoft.com/netfx/2009/xaml/presentation"
xmlns:validationRules="clr-namespace:SWallTech.ValidationSupport;assembly=SWallTech.ValidationSupport"
xmlns:FieldSheetPrinter_Converters="clr-namespace:FieldSheetPrinter.Converters"
xmlns:Converters="clr-namespace:SWallTech.WPF.Support.Converters;assembly=SWallTech.WPF.Support"
x:Class="FieldSheetPrinter.MainWindow"
x:Name="MainWindow"
Title="CAMRA Field Sheet Printer - Stonewall Technologies, Inc."
Width="744"
Height="583"
WindowStartupLocation="CenterScreen"
Icon="CamraPrint.ico">
I have references to the SWallTech.WPF.Support project, which is in the solution, and the compiler has no problem recognizing the classes in that project's Converters namespace. This code has no error indicator. (Red squiggles.)
<Converters:IntGreaterThanZeroToVisibilityConverter
x:Key="IntGreaterThanZeroToVisibilityConverter" />
<Converters:DatabaseConnectionImageSourceConverter
x:Key="DatabaseConnectionImageSourceConverter" />
However if I try to refer to the ViewModel I am using as the datasource, I get an error:
<local:FieldSheetPrinterViewModel
x:Key="FieldSheetPrinterViewModelDataSource"
d:IsDataSource="True" />
I also get the error that the XAML form itself is not in the namespace FieldSheetPrinter, which of course it is, as you can see from the Code-Behind.
namespace FieldSheetPrinter
{
public partial class MainWindow : Window
...
}
I have tried everything I can think of, and I am truly stumped.
Joey

As suggested above, the problem wasn't directly with the XAML, or at least not completely. The original developer had named the Window tag with the same name as the code-behind class name, and that seems to be prohibited now. That was the only issue with the XAML. Everything else had to do with overlaps in the WPF and Windows.System.Data libraries that caused IValueConverter (in the System.Windows.Data namespace) to go unrecognized. I eliminated any other references that could have conflicted, and corrected some syntax issues in the code-behind that apparently were deprecated.
Ex.
stringVariable.IsNullOrEmpty()
was used instead of
string.IsNullOrEmpty(stringVariable)
In other places some ObservableCollection objects weren't recognized as enumerable, so I had to add "ToList()" before looping through the collection.
Weird, but I didn't write this stuff!
Thanks for the suggestions.
Joey

Related

Error Occurred Loading Resource Dictionary

I've looked at and tried these other solutions that I've found, and even copied Telerik's Documentation. However, I still can't get a working solution.
XAML:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="NotifyIconResources.xaml" />
<ResourceDictionary Source="pack://application:,,,/Telerik.Windows.Themes.Windows8;component/Themes/System.Windows.xaml" />
<ResourceDictionary Source="pack://application:,,,/Telerik.Windows.Themes.Windows8;component/Themes/Telerik.Windows.Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/Telerik.Windows.Themes.Windows8;component/Themes/Telerik.Windows.Controls.Navigation.xaml" />
</ResourceDictionary.MergedDictionaries>
Here is an image of the error that ReSharper is giving:
Here's an image of the assembly being a reference:
Here's an image of the assembly properties:
Lastly, here's the exception information when I try to run the app:
System.Windows.Markup.XamlParseException was unhandled
HResult=-2146233087
Message='Cannot create unknown type '{clr-namespace:Telerik.Windows.Controls.External}Windows8ThemeExternal'.' Line number '15' and line position '6'.
Source=PresentationFramework
LineNumber=15
LinePosition=6
StackTrace:
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at MyApp.App.InitializeComponent() in App.xaml: line 1
at MyApp.App.Main() in c:\MyApp\obj\Debug\App.g.cs: line 0
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Xaml.XamlObjectWriterException
HResult=-2146233088
Message='Cannot create unknown type '{clr-namespace:Telerik.Windows.Controls.External}Windows8ThemeExternal'.' Line number '15' and line position '6'.
Source=System.Xaml
LineNumber=15
LinePosition=6
StackTrace:
at System.Xaml.XamlObjectWriter.WriteStartObject(XamlType xamlType)
at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
InnerException:
The first thing that I know IS wrong and that has to be added, according to Telerik documentation,
They can be merged in the resources of your application (in App.xaml) and as a result will be applied implicitly on any control that does not have a local Style set. For example, if you need to style a control from Telerik.Windows.Controls.dll, you need the Telerik.Windows.Controls.xaml resource dictionary.
That being said you're missing a ResourceDictionary for DataVisualization. If that doesn't solve the problem, keep reading.
Last I recall, when I was looking at theme'ing my application using Telerik, there are a couple different ways you can apply styles, and doing it right might be a little tricky at first. There is Implicit Styling (NoXaml) and there is standard styling, where styles are built into the control libraries. Implicit styling is the recommended approach for styling your application in a "global" manner. IIRC, it is also more performant is much more clean in code.
Since we talked in the WPF chat, it sounds like you weren't sure which binaries you were trying to build from source. Implicit styles requires you to build the Binaries.NoXaml source code. After that's said and done, you have to make sure you're adding references to the correct assemblies coming from the ..\Binaries.NoXaml\WPF4x\ directory.
The last time I built from source, the build instructions were included inside the downloaded .ZIP. Make sure you follow those instructions carefully. I have no used built in Visual Studio Telerik tools to build/deploy my referenced libraries, so if you are, then maybe manual is the way to go.
A couple other things. I'm suspicious the build wasn't successfully completed. Your Version # on your Telerik references should be something other than 0.0.0.0. Secondly, if I remember correctly, I had problems with defining the source and possibly the order matters--so try the source that I used in my example below, and maybe move the NotifyIconResources.xaml below the Telerik declarations.
Here is my XAML used with implicit style technique:
<ResourceDictionary Source="/Telerik.Windows.Themes.Windows7;component/Themes/Telerik.Windows.Controls.xaml" />
<ResourceDictionary Source="/Telerik.Windows.Themes.Windows7;component/Themes/System.Windows.xaml" />
<ResourceDictionary Source="/Telerik.Windows.Themes.Windows7;component/Themes/Telerik.Windows.Controls.Input.xaml" />
<ResourceDictionary Source="/Telerik.Windows.Themes.Windows7;component/Themes/Telerik.Windows.Controls.Navigation.xaml" />
As always, starting a new project and getting a basic thing like this working might do you wonders and it will also prevent you from changing so many things in your current code base that you end up forgetting the things you've changed and causing issues in places you don't want them.

WPF: Cannot resolve symbols in code behind

Hi I'm trying to learn a bit of WPF and C# for a project I'm working on. I realised after working for a while that I was going to use couple of the same item and I thought it would be fitting to create my own class to make it easier to use. However now I can't reference elements defined in the XAML in the code behind like I could when just doing it in a window. The error I get is "Cannot resolve symbol 'ThaButton" in the ContactPanel.xaml.cs:
using System.Windows.Controls;
namespace WPF_OOM
{
public partial class ContactPanel : ContentControl
{
public Contact Person { get; set; }
public ContactPanel()
{
ThaButton.Content = "test";
}
}
}
My ContactPanel.xaml
<UserControl x:Class="WPF_OOM.ContactPanel:UserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DockPanel x:Name="dp">
<TextBlock x:Name="NameTextBlock" Text="testtesttest" DockPanel.Dock="Left"></TextBlock>
<Button x:Name="ThaButton" Content="button" DockPanel.Dock="Right"></Button>
</DockPanel>
</UserControl>
Hopefully I've explained my problem well enough. I might have taken the wrong approach to this problem, let me know if there's a better way.
Cheers
Remove :UserControl from x:Class="WPF_OOM.ContactPanel:UserControl" so it looks like x:Class="WPF_OOM.ContactPanel"
Also in your code behind you have the ContactPanel inheriting form ContentControl, but in your xaml it inherits from UserControl. These base classes must match. So change them both to be UserControl or ContentControl
It looks like you created a separate .cs file? I would recommend working with the code behind generated with the xaml file. One way to get to it is in the xaml editor right-click and choose 'View code'. If you imported the xaml and .cs file then reloading the project or restarting visual studio should combine them again in solution explorer if they are not already.
I would suggest looking into the Model-View-ViewModel or MVVM pattern. It works rather nice with WPF ;)
Hope this helps get you started.

Moving MainWindow.xaml

I've built a WPF app, which completely works now. However, to clean it up a bit I wish to move my MainWindow.xaml to the view folder I've created. After I've done this the application won't run and it gives me an "Unknown build error" which doesn't give any info on how to fix it...
What should I change in my MainWindow.xaml to let the app work properly again?
I've already changed
<Window x:Class="projectname.MainWindow">
to
<Window x:Class="projectname.view.MainWindow">
Should I change other stuff as well?
You don't need to update class name in xaml file unless you have changed the namespace of your class.
Most likely you haven't updated StartupUri for App.xaml. Change it to:
StartupUri="view/MainWindow.xaml"
from
StartupUri="MainWindow.xaml"
I just ran into this myself. Here's what I did:
Move your MainWindow.xaml to your new folder. In my case it was /Views.
I like to name all my classes with their namespaces reflecting their folder. So my MainWindow.xaml.cs namespace went from ProjectNamespace to ProjectNamespace.Views
In my MainWindow.xaml, I needed to change x:Class from ProjectName.MainWindow to ProjectName.Views.MainWindow.
In your App.xaml, change the StartupUri to reflect the folder. I went from StartupUri="MainWindow.xaml" to "StartupUri="Views/MainWindow.xaml"`
Doing this allowed me to compile and run my app.
The answer of #Rohit Vats is quite good!
However there's a good point to remember: you have to change all the absolute paths (in XAML) to your resources, prepending them by a / in order to indicate that these paths are relative to the root directory.
Example:
From <Image Source="Assets/Loading.gif">
To <Image Source="/Assets/Loading.gif"> and so on.

Problems with adding EnumMatchToBooleanConverter to my xaml file

I am trying to follow this radiobutton tutorial
I created a class called EnumMatchToBooleanConverter and it is in the top level of my wpf project. It says to place the inside a window.resources like this:
<Window.Resources>
<EnumMatchToBooleanConverter x:Key="enumConverter" />
</Window.Resources>
I am using it in a usercontrol so I have placed it inside a stackpanel instead:
<StackPanel.Resources>
<EnumMatchToBooleanConverter x:Key="enumConverter" />
</StackPanel.Resources>
I have Microsoft Visual Studio Ultimate 2012 and it gives me an error:
EnumMatchToBooleanConverter is not supported in a Windows Presentation Foundation (WPF) project.
Any ideas as to what I am doing wrong? Am I not allowed to place it inside a stackpanel.resources?
I just tried placing it inside a grid.resources
<Grid.Resources>
<EnumMatchToBooleanConverter x:Key="enumConverter" />
</Grid.Resources>
and it says
The type 'EnumMatchToBooleanConverter' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.
Well it is in the same namespace as the rest of my project, so I'm unsure why it isn't finding it.
Change
<EnumMatchToBooleanConverter x:Key="enumConverter" />
for
<local:EnumMatchToBooleanConverter x:Key="enumConverter" />
All non-built-in classes you reference in XAML must be prefixed by their corresponding xmlns prefix.
HighCore's got it right. Just to add to this namespace discussion, I thought I'd point out another approach that can help make the code more readable or help you diagnose where certain Controls/Value Converters/etc are coming from (i.e., which assembly they are really coming from). This technique could allow your XAML to appear like Christian has it in his blog (without the xmlns prefix):
<EnumMatchToBooleanConverter x:Key="enumConverter" />
Essentially you perform some some namespace mappings to consolidate namespaces like this (only works if the files are in a different assembly/project). So in my example above you have mapped one of your namespaces to the default xmlns, so you would not need any prefix in the XAML.
I'm still trying to figure out how far to take this technique and Paul Stovell talks about taking it to the extreme, like I've shown above.
Even if you don't end up applying it to that degree, knowing about it might come in handy if you're looking at someone else's Xaml and they have applied a mapping like that. Knowing that would remind you to lookup the AssemblyInfo.cs file and check for the mapping and possibly help you track down where a Control/Value Converter/etc is actually located.

BlankPage constructor cannot initialize components

I'm starting learning XAML and I add some code to my BlankPage application. And suddenly a constructor which is initializing a component:
public BlankPage()
{
this.InitializeComponent();
}
Stop working. I've got now that error:
'BlankApplication.BlankPage' does not contain a definition for 'InitializeComponent' and no extension method 'InitializeComponent' accepting a first argument of type 'BlankApplication.BlankPage' could be found (are you missing a using directive or an assembly reference?)
Honestly I didn't do anything, I didn't even look at this part of code and now it doesn't work.
Screenshot:
Just to give a bit more information on how to fix this (since this explanation is a bit on the vague side)..
This issue (for me) was caused because I changed the namespace in the code after I created the project. In order to fix this issue I had to make some changes in a couple of locations:
1: In App.xaml I had to change the following:
<Application
x:Class="New.Namespace.App"
2: In MainPage.xaml I had to change the following:
<Page
x:Class="New.Namespace.MainPage"
You will also want to make sure that you change the 'namespace' line in your App.xaml.cs as well as your MainPage.xaml.cs.
Finally, you will also want to make sure you update the Project Entrypoint in the Package.appxmanifest to point to "New.Namespace.App".
If your Main class's namespace is different than .xaml file's x:Class attribute, you will get this error. For instance;
Your MainPage.xaml.cs;
namespace UWPControls
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
}
Your MainPage.xaml;
<Page
x:Class="UWPControls_Different.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UWPHelloWorld"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
</page>
You're going to see the error until changing x:class to the;
x:Class="UWPControls.MainPage"
This happens when you change a namespace for a class, you must do the same inside the XAML file.
There are two places inside the XAML file with the old namespace.
For me, the project was inside solution with other projects. When suggestions here did not work, a simple unloading and reloading the project from solution did the trick and fix all errors (with rebuilding of course).
My Solution: For my "SomePage : ContentPage", I changed the XAML properties:
Generator (Custom Tool): From MSBuild:Compile to MSBuild:UpdateDesignTimeXaml
BuildAction: From Page to Embedded resource
Using Visual Studio 2017 Enterprise 15.3.4
Problem solved.
Cause: I forgot to also change custom application name in xaml code.
Solution: I have changed application name in XAML, now it works well.

Categories

Resources