I'm working through the book Head First C# and consistently have issues when adding resources to a window. This is a 100% repeatable error on any new WPF application I create when adding a new resource. The only way around this is to comment out the resource, build, and uncomment, as detailed in MVCE below. Images are included as proof this isn't a what-if or theoretical scenario.
What are the proper steps to add a resource file and use it within a WPF project?
I'm using Visual Studio Community 2017: Version 15.9.9
Target framework: .NET Framework 4.6.1
MVCE:
Create a new WPF application. Add a class:
//MyDataClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XAMLBuildErrorExample
{
class MyDataClass
{
public string Foo { get; set; }
}
}
Within MainWindow.xaml add a resource
<Window x:Class="XAMLBuildErrorExample.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:XAMLBuildErrorExample"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<local:MyDataClass x:Key="exampleResource" />
</Window.Resources>
<Grid>
</Grid>
</Window>
Attempt to build. Error "The tag 'MyDataClass' does not exist in XML namespace 'clr-namespace:XAMLBuildErrorExample'. Line 11 Position 10.":
Comment out the resource. Build succeeds:
Uncomment resource. Build succeeds whereas it failed before:
Any subsequent cleaning of the solution makes building impossible because of the error in the first image.
It appears the problem is tied to initial computer.
Tested on another work station VS Community 2017 version 15.9.11 and build was successful without any issues. Build>Clean>Build without issues.
Related
I decompiled a .dll with ILSpy and the code looks fine but I have a xaml file which is:
<Window x:Class="PrinterManager.ShellView" 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:PrinterManager" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="Printer Manager" Height="450" Width="400" ResizeMode="NoResize" Icon="C:\Program Files (x86)\CENSURED" WindowState="Minimized" ShowInTaskbar="False" Visibility="Hidden">
.....MORE XAML STUFF....
<Style x:Key="btnStyle" TargetType="{x:Type Button}">
....MORE XAML....
And I have a bunch of errors:
Severity Code Description Project Path File Line Suppression State
Error CS0102 The type 'ShellView' already contains a definition for '_contentLoaded' PrinterManager C:\Users\PietroConvalle\Documents\DotNetDecompileThingy\source\PrinterManager\obj\Debug\net5.0-windows C:\Users\PietroConvalle\Documents\DotNetDecompileThingy\source\PrinterManager\obj\Debug\net5.0-windows\shellview.g.cs 44 Active
Error CS0111 Type 'ShellView' already defines a member called 'InitializeComponent' with the same parameter types PrinterManager C:\Users\PietroConvalle\Documents\DotNetDecompileThingy\source\PrinterManager\obj\Debug\net5.0-windows C:\Users\PietroConvalle\Documents\DotNetDecompileThingy\source\PrinterManager\obj\Debug\net5.0-windows\shellview.g.cs 51 Active
Error CS0111 Type 'ShellView' already defines a member called 'System.Windows.Markup.IComponentConnector.Connect' with the same parameter types PrinterManager C:\Users\PietroConvalle\Documents\DotNetDecompileThingy\source\PrinterManager\obj\Debug\net5.0-windows C:\Users\PietroConvalle\Documents\DotNetDecompileThingy\source\PrinterManager\obj\Debug\net5.0-windows\shellview.g.cs 71 Active
And many more
But if I just remove x:Class="PrinterManager.ShellView" the errors are gone and it builds and runs fine.
I'm sure it's a trivial fix but I never coded in C#, I suspect that's some dependency or config issue?
Sorry can't share the full source for copyright reasons but happy to share a few extra bits if it helps.
Exported with latest ILSpy stable, c# 10.0 / VS 2022
UPDATE: this seems like my issue https://stackoverflow.com/a/25849873/8340761 but I'm not sure what I'm supposed to change?
To fix it I just had to move each .xaml file next to the same file name .cs
This issue was actually fixed in ILSpy 8
I have a peculiar problem regarding internal classes used from xaml.
The problem is as follows:
We decided to strong-name all our assemblies. After the strong-naming, all but one project compiles without a hitch under VS 2017. The situation is as follows:
Assembly Company.Component - Compiles without problems, and exposes its internals as follows:
[assembly: InternalsVisibleTo("Company.Component.Test, PublicKey={omitted}")]
[assembly: InternalsVisibleTo("Company.OtherLibrary, PublicKey={omitted}")]
Assembly Company.Component.Test - Compiles without problems, and can access internals in Company.Component just fine. All tests pass.
Company.OtherLibrary - Does not compile at all, due to the following error in one of its xaml files:
Only public or internal classes can be used within markup. 'Converter1' is not public or internal.
The xaml file in question can be seen below (with names changed):
<ns:class x:Class="Company.OtherLibrary.Class"
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:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:converters="clr-namespace:Company.Component.Converters;assembly=Company.Component"
xmlns:viewModels="clr-namespace:Company.OtherLibrary.ViewModels"
xmlns:ns="clr-namespace:Company.Component;assembly=Company.Component"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
d:DataContext="{d:DesignInstance d:Type=viewModels:ViewModelClass}"
Style="{StaticResource {x:Type ns:Style}}">
<UserControl.Template>
<ControlTemplate>
<DockPanel>
<DockPanel.Resources>
<converters:Converter1 x:Key="Converter1" />
<converters:Converter2 x:Key="Converter2" />
<converters:Converter3 x:Key="Converter3" />
<converters:Converter4 x:Key="Converter4" />
</DockPanel.Resources>
...
</DockPanel>
</ControlTemplate>
</UserControl.Template>
Now to answer some questions:
The public key is the correct public key (not only the token) of the OtherLibrary assembly. It is in fact the same one used for the test assembly.
The assembly name for OtherLibrary is the same as the one in its properties.
The code worked before the strong naming. No changes have been made to any code file in the projects (bar AssemblyInfo.cs). I have checked with VS 2017 git compare. The edited lines are the ones shown, and the edit is to insert public keys.
The xaml-namespaces can sometimes be found, and sometimes not. This only goes for the namespaces that have no public classes.
All converters seen in the dock panel resources are internals in the Company.Component assembly. They all give the following error:
The type '{type}' is not accessible.
All libraries are built against the same version of the framework/dlls.
The assembly reference to Company.Component have 'copy local' set to true.
What I've tried
Clearing xaml shadow-cache
Cleaning and rebuilding.
Changing active build-configuration (both platform and Debug/Release).
Manually cleaning all bin and obj directories for all projects.
Restarted both computer and VS 2017.
All of the above at once.
There is something very simple that I've obviously overlooked. Can someone please help me figure out what is going on here? I am not allowed (for reasons left out) to change the component library other than strongly naming it.
I am very new to WPF programming, so please forgive if this is an obvious mistake on my part. I have a UserControl object that has the following Xaml:
<UserControl x:Class="SDMAS.LOOPAnalyzer.Views.Workspace"
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:dg="http://schemas.microsoft.com/wpf/2008/toolkit"
xmlns:local="clr-namespace:SDMAS.LOOPAnalyzer.Models" >
<UserControl.Resources>
<!-- create an instance of our DataProvider class -->
<ObjectDataProvider x:Key="tblLOOPDataProvider" ObjectType="{x:Type local:tblLOOPDataProvider}"/>
<!-- define the method which is invoked to obtain our data -->
<ObjectDataProvider x:Key="LOOPEvents" ObjectInstance="{StaticResource tblLOOPDataProvider}" MethodName="GetData"/>
</UserControl.Resources>
<DockPanel DataContext="{Binding Source={StaticResource LOOPEvents}}">
<dg:DataGrid ItemsSource="{Binding}" Name="dataGrid"/>
</DockPanel>
</UserControl>
This code actually works. The records from the data table are correctly displayed in the application's view. The problem is the Visual Studio designer for this control thinks there is a problem, complaining about not being able to find the object type in the namespace: ObjectType="{x:Type local:tblLOOPDataProvider}"
The namespace does exist, and does contain the class, as proven by the fact the code is working. So what gives with the designer?
The following is screenshot of the error message:
Here is the tblLOOPDataProvider code
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SDMAS.LOOPAnalyzer.Models.LOOPDataSetTableAdapters;
namespace SDMAS.LOOPAnalyzer.Models
{
/// <summary>
/// Provides a singleton instance of the LOOPDataSet
/// </summary>
public class LOOPDataProvider
{
private static LOOPDataSet _loopDataSet;
public static LOOPDataSet LOOPDataSet
{
get
{
if (_loopDataSet == null)
{
_loopDataSet = new LOOPDataSet();
}
return _loopDataSet;
}
}
}
/// <summary>
/// A source of LOOP event objects
/// </summary>
public class tblLOOPDataProvider
{
private tblLOOPTableAdapter _adapter;
public tblLOOPDataProvider()
{
LOOPDataSet dataset = LOOPDataProvider.LOOPDataSet;
_adapter = new tblLOOPTableAdapter();
_adapter.Fill(LOOPDataProvider.LOOPDataSet.tblLOOP);
dataset.tblLOOP.tblLOOPRowChanged += new LOOPDataSet.tblLOOPRowChangeEventHandler(tblLOOPRowModified);
dataset.tblLOOP.tblLOOPRowDeleted += new LOOPDataSet.tblLOOPRowChangeEventHandler(tblLOOPRowModified);
}
void tblLOOPRowModified(object sender, LOOPDataSet.tblLOOPRowChangeEvent e)
{
_adapter.Update(LOOPDataProvider.LOOPDataSet.tblLOOP);
}
public DataView GetData()
{
return LOOPDataProvider.LOOPDataSet.tblLOOP.DefaultView;
}
}
}
Since I first posted this I have been hacking at various parts of the project, and now the designer won't display the Xaml at all. Just says Loading Designer... and appears to hang.
Some more background. I started this project based on the Prism4Demo on CodeProject (by David Veeneman). It has changed much since it's beginning, migrating to Prism 6 and updating other dependencies. That demo seemed a good template for an application that will have a number of modules to be developed independently by different staff members, likely with only one professional programmer to provide integration (not me). The class creating the designer problem is the "workspace" view for one of the modules that will eventually be wired to a view-model that in turn will be wired to a model consisting of a DataSet representing a LOOP event data table on a SQL server. In this current learning step, I have connected the server data table to a DataSet, which I am displaying in the workspace view directly without the view-model in the middle (and it is working, aside from the designer issue). I have based the code on internet examples that I don't yet understand all the way, but have been able to make work. So I don't yet understand the reason for the LOOPDataProvider class complexity, or the use of Resources in the Xaml.
So I continue to study the MVVM structure and my next step will be to wire up the DataSet-based model to the view-model, and the view-model to the view.
I am running Visual Studio 2013 Community Update 4 on x64 Windows 8.1 with all available updates applied as of 30-Dec-2014. I am running Windows 8.1 on VMWare Fusion 7 on a MacBook Pro w/ 2 processors and 4Gig allocated. Using C#, standard Blank template, and adding my own custom class. I have added the namespace to the MainPage.xaml:
<Page
x:Class="BindingWithValueConverters.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BindingWithValueConverters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:valueconverter="using:BindingWithValueConverters.Converters"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
DataContext="{Binding WeatherViewModel, RelativeSource={RelativeSource Self}}">
<Page.Resources>
<valueconverter:DateToStringConverter x:Key="DateToStringConverter" />
</Page.Resources>
...
The "red squiggly" line remains under "valueconverter:DateToStringConverter"; If I delete the line, and start typing, "va..." Intellisense picks up "valueconverter:", so the namespace is "there". Then, the "DateToStringConverter" class shows as an option on autocomplete. Once accepted, after a brief delay, the red squiggly comes back specifying:
The type "DateToStringConverter" is not accessible.
The code builds and runs with no errors. I could continue to code, blindly. It would be optimal to fix this issue, though. Would appreciate guidance.
I have cleaned the project. I have deleted the *.suo file. The phone emulator runs as it does on a non-VM. I have run this exact project on a Windows 8.1 machine (no VM), and do not have this issue. I suspect Intellisense. Here is my converter class if helpful:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace BindingWithValueConverters.Converters
{
class DateToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
//throw new NotImplementedException();
DateTime date = (DateTime)value;
return String.Format("{0:dddd} - {0:d}", date);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
VMWare/Mac is the obvious difference between working and not; however, I am hopeful there is a parameter missing on my VMWare deployment or Visual Studio deployment regarding Intellisense that could resolve this. Intellisense is working everywhere else within this project.
Thanks!
Your converter class has not been given an explicit access modifier. Make it public and it'll show up just fine.
public class DateToStringConverter : IValueConverter
I have really strange problem. I've created WPF project in 2012 or 2013 VS it doesn't matter. I use .NET 4.5.
I add a new Activity (Workflow class) to that project. Its name is CustomActivity.
Then I add a new class that has got an attached property, example below:
public class AttachedObject : DependencyObject
{
public static readonly DependencyProperty NameProperty = DependencyProperty.RegisterAttached(
"Name",
typeof(string),
typeof(AttachedObject),
new FrameworkPropertyMetadata(
string.Empty,frameworkPropertyMetadataOptions.AffectsRender));
public static void SetName(ContentControl element, string value)
{
element.SetValue(NameProperty, value);
}
public static string GetName(ContentControl element)
{
return (string)element.GetValue(NameProperty);
}
}
The last step is to change MainWindow class that way:
public MainWindow()
{
InitializeComponent();
var activity = new CustomActivity();
}
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication1="clr-namespace:WpfApplication1;assembly=WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ContentControl wpfApplication1:AttachedObject.Name="MainArea"/>
</Grid>
</Window>
The problem is it doesn't compile because of below error:
Error 1 The type or namespace name 'CustomActivity' could not be found (are you missing a using directive or an assembly reference?) WpfApplication1\MainWindow.xaml.cs 13 32 WpfApplication1
CustomActivity has a default namespace. In obj folder there is CustomActivity.g.cs generated, so I have no idea what's going on.
It's 100% reproducible. When I remove using of CustomActivity or using of AttachedObject from xaml then the problem disappear.
Try replacing this:
xmlns:wpfApplication1="clr-namespace:WpfApplication1;assembly=WpfApplication1"
with this
xmlns:wpfApplication1="clr-namespace:WpfApplication1"
The error you're seeing is due to a "known" issue in WPF applications that xaml namespaces that reference clr namespace from current assembly your in don't require the full assembly qualified name. If you were to declare a xaml namespace that references a clr namespace from another assembly, than you would have to specify the full name (with the ;[assemblyname] syntax).
Workflow Foundation has nothing to do with it.
EDIT:
Didn't realize it was a xaml activity.
But still, you can make it work, maybe, with a few hacks, but I wouldn't recommend it.
The reason you get that error is due to the different code generation and build action VS uses when creating xaml artifacts for WPF (Page):
System.Windows.Application.LoadComponent(this, resourceLocater);
and when creating xaml activities (XamlAppDef):
typeof(CustomActivity).Assembly.GetManifestResourceStream(resourceName);
If you turn your CustomActivity xaml build action to Page, the whole thing will compile - but i'm guessing something else might be broken someplace else...or not, who knows. My guess is that these two kinds of xaml were not meant to live together in a VS WPF application project template. But you can still define activities in a WF activity library, that way your activities will also be more easily reusable for other projects, WPF, console or even services.
I have the same issue under Visual Studio 2017.
The problem in my case is that Visual Studio is not compiling the Workflow activities before the code that use them.
To fix it, what I did is to move all workflows to other project dll, so visual Studio is forced to compile the workflows before the classes that make use of them.