WPF/XAML (Window.Resources) cannot find ClassName in NameSpace - wpf

I have a problem that I have spent a lot of time to resolve in vain.
I have created a class name in spacename "ComboBoxDGWPF":
public class StatusList : List<string>
{
public StatusList()
{
this.Add("Assigned");
this.Add("Closed");
this.Add("In Progress");
this.Add("Open");
this.Add("Resolved");
}
}
In XAML, I create a staticData like that:
<Window x:Class="ComboBoxDGWPF.Window1"
....
xmlns:staticData="clr-namespace:ComboBoxDGWPF"
....
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<staticData:StatusList x:Key="StatusList"/>
</Window.Resources>
....
</Window> <!-- Added by edit -->
But in XAML it gives me an error:
the name 'StatusList' does not exist in NameSpace 'clr-namespace:ComboBoxDGWPF'.
I'm 100% sure that there is the 'public class StatusList' in that namespace.
I don't understand why this error occurs?
See attached code source for details.

Related

WPF, Simple Injector and MaterialDesignThemes Static resource invalid

I have sample app written in WPF and using Simple Injector and Material Design Themes.
This is my program file:
private static Container Bootstrap()
{
// Create the container as usual.
var container = new Container();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
// Register your types, for instance:
container.Register<IFreewayReviewCreatorDbContext, FreewayReviewCreatorDbContext>(Lifestyle.Scoped);
container.Register<IUnitOfWorkFactory, UnitOfWorkFactory>(Lifestyle.Transient);
container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Scoped);
container.Register<IReviewBodyBLL, ReviewBodyBLL>(Lifestyle.Transient);
// Register your windows and view models:
container.Register<MainWindow>();
container.Register<MainWindowViewModel>();
container.Verify();
return container;
}
private static void RunApplication(Container container)
{
try
{
var app = new App();
//app.InitializeComponent();
var mainWindow = container.GetInstance<MainWindow>();
app.Run(mainWindow);
}
catch (Exception ex)
{
//Log the exception and exit
}
}
In the code above view models add registered in Simple Injector.
Now in MainWindow I want to use StaticResource from Material Design. This is my code:
<Window x:Class="FreewayReviewCreator.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:FreewayReviewCreator"
xmlns:localvm="clr-namespace:FreewayReviewCreator.ViewModel"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
mc:Ignorable="d" Loaded="MainWindow_OnLoaded"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel HorizontalAlignment = "Left">
<TextBox
Name="tbxPassword"
Text="{Binding Password, Mode = TwoWay}"
HorizontalContentAlignment="Center"
Style="{StaticResource MaterialDesignFloatingHintTextBox}"
MaxLength="28"
materialDesign:HintAssist.Hint="Enter your username"
/>
Error is in this line: Style="{StaticResource MaterialDesignFloatingHintTextBox}":
System.Windows.Markup.XamlParseException: ''Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '44' and line position '21'.' Exception: Cannot find resource named 'MaterialDesignFloatingHintTextBox'. Resource names are case sensitive.
On this webpage is sample application with StaticResource (I took code from this app):
https://www.c-sharpcorner.com/article/wpf-application-with-googles-material-design/
and it works. The only one difference that I can see is that my application has Simple Injector and app from sample doesn't have.
References are the same in both of apps:
You should install the MaterialDesignThemes NuGet package and add the following resource dictionaries to your App.xaml file as described in the docs:
<?xml version="1.0" encoding="UTF-8"?>
<Application . . .>
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
This has nothing to do with simple injector or whatever IoC container you are using.
You need to import the resources into your app to be able to use them.
Assuming you provide the ResourceDictionaries to the App class as given in the answer of #mm8, you should load and apply the ResourceDictionaries by calling InitializeComponent() in the constructor of the App class.
Like this:
public partial class App : Application
{
public App()
{
this.InitializeComponent();
}
}
I see in your question that commented this line out. This is probably the result of following the provided startup code from Simple Injector documentation and after this adding the Material Design Themes.
This code is however necessary when you add MergedDictionaries to you App.xaml. So you need to add it back.

XAML.Parse.Exception on WPF project's deployment

I'm having a problem when I deploy my WPF project, the deployed project crashes on startup and produces a XAML.Parse.Exception with an inner exception of "Cannot have nested BeginInit calls on the same instance" at Line 4 Position 70. The App has full permissions on my computer. I am asking this question because the few questions asked about this had no real solution to the problem.
Here is the XAML code it is referencing with the first couple of lines.
<Window
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" x:Class="ASRV.MainWindow"
Title="ASRV GUI" Height="768" Width="1024" ResizeMode="CanMinimize">
<Window.Resources>
</Window.Resources>
<Window.Background>
<ImageBrush ImageSource="pack://siteoforigin:,,,/background.png"/>
</Window.Background>
My guess is the reason being:
<Window.Background>
<ImageBrush ImageSource="pack://siteoforigin:,,,/background.png"/>
</Window.Background>
You might be reusing this image elsewhere in the same window or subcontrol.
BeginInit is called in databinding and this is the only databound thing I could see in your sample code. "BeginInit calls on the same instance" points to it being bound twice.
This error is encountered whenever an object is attempted to be bound twice, as #basarat says in his answer. Further to the example seen in the OP, I came across this same error caused in my case by setting a DataContext in the CodeBehind as well as in the xaml:
In the MainWindow.xaml file, I had the following:
<Window xmlns:vm="clr-namespace:MyApp.ViewModel"
[...more xmlns references skipped for brevity...]
<!--the next three lines caused a problem, when combined with the code behind-->
<Window.DataContext>
<vm:MainViewModel/>
</Window.DataContext>
</Window>
And in the MainWindow.xaml.cs file, I had this:
namespace MyApp.View
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainViewModel MainViewModel { get; set; }
public MainWindow()
{
bool success = false;
MainViewModel = new MainViewModel();
// This line caused the problem in combination with the xaml above
DataContext = MainViewModel;
InitializeComponent();
}
}
}
In order to get rid of the problem, I deleted one of the DataContext setters; it works with either the data context set in xaml or the data cantext set in the code behind, not both.
P.S. I add this answer because this is the first answer to come up on searches for this problem and I felt that further explanation would be useful to other visitors.

Setting Window.Datacontext

I am trying to use my viewmodel as my window's datacontext but am getting the error:
ViewModel is not supported in a Windows Presentation Foundation (WPF) project.
Clearly, I am not understanding something about the syntax and databinding my window to my view model, but I am not sure what it is that I don't know.
Any advice on what I should be reading?
<Window x:Class="SunnyBeam.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SunnyBeam" Height="488.358" Width="1014.552">
<Window.DataContext>
<ViewModel/>
</Window.DataContext>
<Grid>
</Grid>
</Window>
Usually I set DataContext through codebehind like that:
public partial class Flor1 : Window
{
public Flor1()
{
var dc = new MyViewModel();
dc.LoadData();
DataContext = dc;
InitializeComponent();
}
}
In place of MyViewModel may be anything you want to bind to.
define class like
public class ViewModel
{
public string Name { get; set; }
public ViewModel()
{
}
}
Use it in xaml like
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<ui:ViewModel/>
</Window.DataContext>
<Grid>
</Grid>
It should work.
I thought I would throw in my experience with this error.
I had my datacontext setup same as below, and kept getting an error that ViewModel didn't exist, which I know it did. I refused to set it in code behind, simply rebuilding my project actually fixed this error.
<Window.DataContext>
<ViewModel/>
</Window.DataContext>

How to add UserControl to a Panel on a WPF Window

I think I'm missing something that should be obvious here, but I'm drawing a blank on this one.
I've built a very primitive UserControl containing nothing more than a TextBox to use as a log window:
<UserControl x:Class="My.LoggerControl"
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"
x:Name="LoggerView">
<Grid x:Name="LayoutRoot">
<TextBox x:Name="LogWindow" AcceptsReturn="True"/>
</Grid>
</UserControl>
I don't expect that to be the best way to do it, but it should be good enough for a prototype.
The code-behind is similarly simple:
public partial class LoggerControl : UserControl, ILogger
{
public LoggerControl()
{
InitializeComponent();
}
private LogLevel level = LogLevel.Warning;
#region ILogger
public LogLevel Level
{
get { return level; }
set { level = value; }
}
public void OnError(string s)
{
if (level >= LogLevel.Error)
LogWindow.AppendText("ERROR:::" + s + "\n");
}
// ...
#endregion
}
The thing I can't figure out is how to add this control to my MainWindow.xaml. Simplifying, lets say my window looks like this:
<Window x:Class="My.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:My"
Title="Test" Height="350" Width="525">
<Grid>
<local:LoggerControl x:Name="LogView" />
</Grid>
</Window>
Even with something so simple, the Designer in Visual Studio 2010 can't load the main window. The error given is:
A value of type 'LoggerControl' cannot be added to a collectionor dictionary of type 'UIElementCollection'.
This error message has only one unrelated hit in the major search engines (plus duplicates) so I haven't found any useful help. Microsoft's own documentation seems to imply that this should work.
Any idea how to solve this?
<UserControl x:Class="My.LoggerControl"
xmlns:local="clr-namespace:My.LogTest"
Looks like you may have made a mistake in the namespacing? LoggerControl is listed as being the namespace My, while you're importing My.LogTest and assigning it to the xml-prefix local. Change this to:
xmlns:local="clr-namespace:My"
And I think it should work. Otherwise, fix the LoggerControl declaration.

Designer rejecting DataTemplate.DataType

I am try to fit some WPF into my current Windows Forms application. When I use this simple user control, the designer for that control does not reload.
This only happens in this application. If I make a clean Windows Forms project, add these files, the designer works fine.
I have tried a reload of Visual Studio, and cleans / rebuilds of the application.
Any ideas? (These are for the items in a ListBox, so x:Key is not an option.)
P.S. How do I get rid of all those trailing blank lines in my code listing?
DETAILS:
MyClasses.cs
namespace MyNamespace {
internal class MyClassInternal {}
public class MyClassPublic {}
}
MyUserControl.xaml
<UserControl x:Class="MyNamespace.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyNamespace"
Height="300" Width="300">
<UserControl.Resources>
<DataTemplate DataType="{x:Type local:MyClassInternal}"/> <!--OK-->
<ObjectDataProvider x:Key="ClassPublicKey" ObjectType="{x:Type local:MyClassPublic}"/> <!--OK-->
<!-- Type reference cannot find public type named 'MyClassPublic' -->
<DataTemplate DataType="{x:Type local:MyClassPublic}"/> <!--FAILS-->
</UserControl.Resources>
<TextBlock>Hello World</TextBlock>
</UserControl>
MyUserControl.xaml.cs
using System.Windows.Controls;
namespace MyNamespace {
public partial class MyUserControl :UserControl {
public MyUserControl() {
InitializeComponent();
}
}
}
It was caused by having a space in the Assembly name.

Resources