Set Command property of CommandBinding using internal namespace with custom commands? - wpf

I'm exploring WPF and seeing if I can work my way to using a full MVVM approach. For now, I think I need to learn how to reference my own custom objects/commands that I've defined in a nearby namespace.
This is my folder structure:
This is my XAML
<Window x:Class="WpfApp1.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:WpfApp1"
xmlns:commands="clr-namespace:WpfApp1.Commands"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.CommandBindings>
<CommandBinding
Command="commands:WordSearchCommand"
CanExecute="CanExecuteChanged"/>
</Window.CommandBindings>
<Grid>
<StackPanel Orientation="Horizontal">
<Label Target="{Binding ElementName=wordSearchBox}">Word _Search:</Label>
<TextBox
Name="wordSearchBox"
Height="25"
Width="600"
VerticalAlignment="Top"
SpellCheck.IsEnabled="True"
Text="{Binding Path=SearchWord}">
</TextBox>
<Button Height="25" Width="100" VerticalAlignment="Top" Command="{Binding Path=WordSearchCommand}" CommandParameter="{Binding Path=SearchWord}">Search</Button>
</StackPanel>
</Grid>
</Window>
This is my MainWindow code-behind:
using AppLogicCommandsAndQueries;
using System.Windows;
using WpfApp1.ViewModels;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
Bootstrapper.Bootstrap();
InitializeComponent();
DataContext = new WordSearchViewModel();
}
}
}
This is my WordSearchCommand definition:
using System;
using System.Windows;
using System.Windows.Input;
namespace WpfApp1.Commands
{
public class WordSearchCommand : ICommand
{
private string previousSearch;
public event EventHandler CanExecuteChanged = delegate (object s, EventArgs e)
{
MessageBox.Show("word search can execute changed");
};
public bool CanExecute(object parameter)
{
return previousSearch != (string)parameter;
}
public void Execute(object parameter)
{
// if online check online db else check offline db
MessageBox.Show("word search command");
previousSearch = (string)parameter;
}
}
}
I've tried rebuilding, switching CPU targets, switching to Release mode and back, etc. There's got to be a coding error, right?
This is the error displayed in my build output:
WpfApp1\MainWindow.xaml(14,134,14,151): error CS1061: 'MainWindow' does not contain a definition for 'CanExecuteChanged' and no accessible extension method 'CanExecuteChanged' accepting a first argument of type 'MainWindow' could be found (are you missing a using directive or an assembly reference?)

It seems like I don't understand C# events or WPF event routing very well. I was able to get the desired behavior by changing the CanExecuteChanged event handler on my WordSearchCommand.
Before I had:
public event EventHandler CanExecuteChanged = delegate (object s, EventArgs e)
{
MessageBox.Show("word search can execute changed");
};
Which would never execute (I never saw the message box). Also, the CanExecute method would only get called once.
Now, I have:
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
and now my CanExecute method gets called a ton (a bunch at the beginning, and basically anytime I interact with the Window?).
I tried adding event accessors before but didn't realize I needed to remove the delegate signature for the accessor definitions to become syntactically valid. I definitely took inspiration from a RelayCommand definition as well as other posts on StackOverflow. I'm still not exactly sure what's going on here, but I've stumbled upon a solution that I can use for now.

Related

Microsoft WPF Designer Value For Property Not Updating When Changed By Another Property

Similar questions have been asked for WinForms projects, but not for WPF projects.
This VERY simple sample below shows the issue. The real user control I have is much more complicated but this sample shows the basic issue I am having.
The UserControl1 xaml (nothing there as it doesn't need anything to show the issue)
<UserControl x:Class="TestProperty.UserControl1"
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"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
</Grid>
</UserControl>
The Window xaml (just contains a UserControl1):
<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"
xmlns:TestProperty="clr-namespace:TestProperty;assembly=TestProperty" x:Class="TestApp.MainWindow"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TestProperty:UserControl1 HorizontalAlignment="Left" Height="100" Margin="10,10,0,0" VerticalAlignment="Top" Width="100"/>
</Grid>
</Window>
The actual Window code-behind is really nothing
using System.Windows;
namespace TestApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
Here is code-behind for UserControl1. Has two properties where the first property simply modifies the second to be the same.
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace TestProperty
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
[Description("Sets a test property value that sets another property.")]
[Category("UserControl1")]
[RefreshProperties(RefreshProperties.All)]
public bool TestValue1
{
get => (bool) GetValue(TestValue1Property);
set => SetValue(TestValue1Property, value);
}
public static readonly DependencyProperty TestValue1Property =
DependencyProperty.Register(
"TestValue1", typeof(bool), typeof(UserControl1),
new FrameworkPropertyMetadata(false,
new PropertyChangedCallback(TestValue1Changed)));
private static void TestValue1Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) =>
((UserControl1) d)?.TestValue1Changed(e);
private void TestValue1Changed(DependencyPropertyChangedEventArgs e)
{
TestValue2 = (bool) e.NewValue;
InvalidateProperty(TestValue2Property);
}
[Description("Value should change automatically when TestValue1 changes.")]
[Category("UserControl1")]
[RefreshProperties(RefreshProperties.Repaint)]
public bool TestValue2
{
get => (bool) GetValue(TestValue2Property);
set => SetValue(TestValue2Property, value);
}
public static readonly DependencyProperty TestValue2Property =
DependencyProperty.Register(
"TestValue2", typeof(bool), typeof(UserControl1),
new FrameworkPropertyMetadata(false,
new PropertyChangedCallback(TestValue2Changed)));
private static void TestValue2Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) =>
((UserControl1) d)?.TestValue2Changed(e);
private void TestValue2Changed(DependencyPropertyChangedEventArgs e)
{
InvalidateProperty(TestValue2Property);
}
}
}
The attribute RefreshProperties and the call to InvalidateProperty appear to do nothing.
When editing the MainWindow.xaml and selecting UserControl1, the UserControl1 section of the Properties window shows TestValue1 and TestValue2. If TestValue1 is changed, TestValue2 does NOT change. However, if you change to another Visual Studio (or Blend) editor window and then back to the MainWindow.xaml, then TestValue2 will be the same as TestValue1.
I cannot seem to find any method to automatically have TestValue2 update when TestValue1 forces the update. The real case is obviously more complex with quite a few controls and when adding our UserControl, we want the designer to be able to specify several properties that can result in forcing (or coercing) other properties. However, the designer needs to be able to see the property value changes without having to switch to another file and back again to redraw the designer's properties window.
Is this something that simply can't be done - or is there something I'm missing. Note that this is a UserControl and is not designed to operate itself MVVM, but allow another window to be designed using the control with (or without) MVVM design.
Also, in a 'kind of' related issue. We have one property that needs to have an entry in the properties the same as Width and Height with the auto button. When set to Auto display "Auto (nnn)" as the automatically set value changes nnn changes. When not set, the value is simply nnn and is defined during the design of the window using the UserControl. Is this possible?
Thanks in advance to anyone who can shed light on this.

WPF vs. Silverlight - DataBinding in resources

after some time of silverlight-development I am currently doing some WPF work...
I often used this trick to make my life easier in some of my ValueConverters:
public class MyCovnerterWithDataContext : FrameworkElement, IValueConverter
{
private MyDataContextType Data
{
get { return this.DataContext as MyDataContextType; }
}
....
Now I could access my DataContext in the Converter-Method, which comes handy in lots of situations as you can imagine.
I tried the same trick in WPF and found out, that unfortunately this does not work at all. There is the following error in the debug-output:
"Cannot find element that provides DataContext"
I suppose the resources aren't part of the visual tree in WPF whereas they are in Silverlight.
So - is my little trick possible in WPF as well?
Is my little trick to be considered a dirty hack?
What's your opinion and suggestions?
Regards
Johannes
Update:
as requested some more info - actually a minimal example:
XAML:
<Window x:Class="WpfDataContextInResources.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfDataContextInResources"
x:Name="window"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:TestWrapper x:Key="TestObj" />
</Window.Resources>
<StackPanel>
<TextBlock Text="{Binding Text}" />
<TextBlock Text="{Binding DataContext.Text, Source={StaticResource TestObj}, FallbackValue='FALLBACK'}" />
</StackPanel>
</Window>
the .cs file:
namespace WpfDataContextInResources
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new DataClass()
{
Text = "Hello",
};
}
}
public class TestWrapper : FrameworkElement {}
public class DataClass
{
public string Text { get; set; }
}
}
At least on my PC the lower text-block stays on the fallbackvalue
Update #2:
I tried the suggestion Matrin posted (deriving from DependencyObject, creating own DependencyProperty, etc) - it did not work either.
This time however the error-message is a different one:
"System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:(no path); DataItem=null; target element is 'TestWrapper' (HashCode=28415924); target property is 'TheData' (type 'Object')"
I also have some suggestions for workarounds though:
1.) - Use MultiBinding --> not compatible with Silverlight, not enough in some cases.
2.) - Use yet another wrapping object, set DataContext by hand in code-behind, like this --> fully compatible with Silverlight (apart from the fact, that you can't use a Framework-Element directly - you have to make an empty class deriving from it)
xaml:
<Window.Resources>
<FrameworkElement x:Key="DataContextWrapper" />
<local:TestWrapper x:Key="TestObj" DataContext="{Binding DataContext, Source={StaticResource DataContextWrapper}}" />
...
code behind:
//of course register this handler!
void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var dcw = this.Resources["DataContextWrapper"] as FrameworkElement;
dcw.DataContext = this.DataContext;
}
There may be a problem with your type being derived from FrameworkElement:
From the msdn page about suitable objects in ResourceDictionaries
[...] Being shareable is required [...]
Any object that is derived from the UIElement type is inherently not
shareable [...]
Derive from DependencyObject instead:
public class TestWrapper : DependencyObject {}

Setting UserControl ViewModel Property

All -
I am using Unity in my WPF application for DI (without prism). I have my MainWindow.xaml and MainWindowViewModel.cs. I have a usercontrol in my Mainwindow.xaml. The user control has its own uc1.xaml and uc1viewmodel.cs. The UC1 ViewModel is currently exposed as a property on MainWindowViewModel so I can set the datacontext on the usercontrol (as recommended by many ppl here).
The question I have is how/where can I set this property - will it be in app.xaml.cs or will it be in the constructor of mainwindowviewmodel. Code Snippets:
App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
//Step 1 - One Time - Creating an instance of the container
UnityContainer unity = new UnityContainer();
//Step 2 - Registering your MainWindowViewModel
unity.RegisterType<IViewModel, UserControl1ViewModel>();
//Step 3 - Creating an Instance
UserControl1ViewModel uc1_mwvm = unity.Resolve<UserControl1ViewModel>(); <-- doesnt help
MainWindowViewModel mwvm = unity.Resolve<MainWindowViewModel>();
MainWindow mw = unity.Resolve<MainWindow>();
mw.Show();
}
MainWindowViewModel.cs
public class MainWindowViewModel
{
public IViewModel IVM { get; set; }
public MainWindowViewModel()
{
//IVM = new UserControl1ViewModel(); <-- All I really want is an equivalent but letting Unity do the work.
}
}
MainWindow.xaml
<Window x:Class="_05_ViewFist_UC_Unity_Working.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uc1="clr-namespace:_05_ViewFist_UC_Unity_Working"
xmlns:uc2="clr-namespace:_05_ViewFist_UC_Unity_Working"
Title="MainWindow" Height="350" Width="525">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding NNN}" />
<uc1:UC1 DataContext="{Binding UC1VM}" />
<uc2:UC2 DataContext="{Binding UC2VM}" />
</StackPanel>
</Window>
UC1
<UserControl x:Class="_05_ViewFist_UC_Unity_Working.UC1"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" >
<StackPanel Orientation="Horizontal" Background="Red">
<TextBlock Text="UC1 " />
<TextBlock Text="{Binding FirstName}" />
</StackPanel>
</UserControl>
As you see from the code - Instance of UC1 is created in xaml (MainWindow.xaml) and hence when MainWindow instance is created in app.xaml.cs - it still doesnt create an instance of UserControl1ViewModel.
Question again is : Dont think its a good practice for me to call the Unity Resolve statement in the constructor of MainwindowViewModel. Is that correct??
Can somebody share a code snippet of how/where I can do this?
Thanks
I downloaded your solution from github and tried to solve your problem.
You did a great job just you forgot few details such as property attributes.
This is how your App.cs file shall look alike:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
//Step 1 - One Time - Creating an instance of the container
UnityContainer unity = new UnityContainer();
//Step 2 - Registeration
unity.RegisterType<IMainWindowViewModel, MainWindowViewModel>();
unity.RegisterType<IUC1ViewModel, UC1ViewModel>();
unity.RegisterType<IUC2ViewModel, UC2ViewModel>();
//// Instance of MainWindowViewModel will be created once you call Resolve MainWindow.
MainWindow mw = unity.Resolve<MainWindow>();
mw.Show();
}
Here is what I changed:
public class MainWindowViewModel : IMainWindowViewModel
{
#region Public Properties
[Dependency]
public IUC1ViewModel UC1VM { get; set; }
[Dependency]
public IUC2ViewModel UC2VM { get; set; }
public string NNN { get; set; }
#endregion
public MainWindowViewModel()
{
NNN = "This value coming from MainWindowViewModel";
}
}
[Dependency] is a property attibute that tells Unity where to inject values.
I could merge my code to your repo in github if you wish so.
Let me know if this helped you any futher. Feel free to mark this as the answer.
You can use the service locator pattern. I use it with Unity as a DI.
internal class ServiceLocator
{
[...]
public MainViewModel Main { get { return container.Resolve<MainViewModel>(); } }
}
You can intantiate your class the way you want (DI or not, the class initializes the DI or receive it as a parameter, you can store the DI in a private static property, you can initialize your class if DI is null or when the application starts etc...).
In your App.xaml
<Application.Resources>
<vm:ServiceLocator x:Key="Locator"/>
</Application.Resources>
And now, you can set your datacontext
DataContext="{Binding Main, Source={StaticResource Locator}}"
Edit:
I found another way of doing it (among other):
Take a look at this article. In the command, you can resolve your viewmodel as you like.

Named Controls inside content property of UserControl always appear null at run time

I have created a user control that I reuse for different purposes. I have defined a Dependency Property that holds a UIElement, which I present as the content of one of the areas in the user control.
I noticed that when I use this control. and give names to the elements inside the content property, they always appear as null at run time.
MyContainer.xaml:
<UserControl x:Class="BSSApp.UI.Tests.MyContainer" x:Name="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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Border x:Name="LayoutRoot" Background="Green" CornerRadius="20" BorderBrush="#005500" BorderThickness="10">
<ContentPresenter Content="{Binding ElementName=userControl, Path=MyContent}" Margin="20"/>
</Border>
</UserControl>
MyContainer.xaml.cs
namespace BSSApp.UI.Tests
{
public partial class MyContainer : UserControl
{
public static readonly DependencyProperty MyContentProperty =
DependencyProperty.Register("MyContent",
typeof(UIElement),
typeof(MyContainer),
new PropertyMetadata(new Grid()));
public UIElement MyContent
{
get
{
return (UIElement)GetValue(MyContentProperty);
}
set
{
SetValue(MyContentProperty, value);
}
}
public MyContainer()
{
InitializeComponent();
}
}
}
And the using class:
UserControlContentBug.xaml:
<UserControl x:Class="BSSApp.UI.Tests.UserControlContentBug"
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:t="clr-namespace:BSSApp.UI.Tests"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<t:MyContainer>
<t:MyContainer.MyContent>
<Button Name="btnWithName" Click="btnWithName_Click">Click Me</Button>
</t:MyContainer.MyContent>
</t:MyContainer>
</Grid>
</UserControl>
and the code behind:
UserControlContentBug.xaml.cs
namespace BSSApp.UI.Tests
{
public partial class UserControlContentBug : UserControl
{
public UserControlContentBug()
{
InitializeComponent();
}
private void btnWithName_Click(object sender, RoutedEventArgs e)
{
// this throws an exception
btnWithName.Tag=2;
}
}
}
So there is a declaration of a button, named "btnWithName". the variable is indeed declared in the code behind, but it holds null... It only happens when the button is declared inside a property of another user control.
Does anybody know how to solve this?
Thanks
I just ran into this problem myself. The generated partial class (e.g., obj\UserControlContentBug.xaml.g.cs) which defines the code-accessible named elements in your XAML uses FrameworkElement.FindName() to make those assignments.
According to MSDN:
A run-time API such as FindName is working against an object tree. These objects are loaded into the content area and the CLR runtime engine of the overall Silverlight plug-in. When part of the object tree is created from templates or run-time loaded XAML, a XAML namescope is typically not contiguous with the entirety of that object tree. The result is that there might be a named object in the object tree that a given FindName call cannot find.
Since MyContainer establishes its own namescope boundary as a UserControl, calling FindName() from UserControlContentBug will not explore that part of the object tree (where
btnWithName is defined).
There are probably a few different ways to work around this, but the simplest one that works for me is to:
Give MyContainer a name (x:Name="myContainer").
Remove the name from the Button (btnWithName) so that the superfluous, always-null variable of the same name isn't reserved in the generated C# code.
Create a reference to the Button in the codebehind.
Like so:
namespace BSSApp.UI.Tests
{
public partial class UserControlContentBug : UserControl
{
private Button btnWithName;
public UserControlContentBug()
{
Loaded += UserControlContentBugLoaded;
InitializeComponent();
}
private void UserControlContentBugLoaded(object sender, System.Windows.RoutedEventArgs e)
{
btnWithName = myContainer.MyContent as Button;
}
private void btnWithName_Click(object sender, RoutedEventArgs e)
{
// this throws an exception, not so much
btnWithName.Tag=2;
}
}
}
Hope this helps.
Try using x:Name instead of Name on the button.

Xaml parse exception is thrown when i define a duplex contract

I've got a WPF application containing a WCF service.
The Xaml code is pretty simple:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Server" Height="308" Width="560" >
<Grid>
<Grid Margin="2,2,0,0" Name="grid1">
<RichTextBox Margin="14,29,12,39" Name="richTextBox1" />
<TextBox Height="24" Margin="16,0,80,9" Name="textBox1" VerticalAlignment="Bottom">Enter your text here</TextBox>
<Button Height="24" HorizontalAlignment="Right" Margin="0,0,12,9" Name="button1" VerticalAlignment="Bottom" Width="63">Send</Button>
<Label Height="23" Margin="16,0,12,0" Name="label1" VerticalAlignment="Top">Address:</Label>
</Grid>
</Grid>
</Window>
Here is the service:
namespace WpfApplication1
{
[ServiceContract(CallbackContract=typeof(IMyCallbackContract))]
public interface IMyService
{
[OperationContract(IsOneWay = true)]
void NewMessageToServer(string msg);
[OperationContract(IsOneWay = true)]
bool ServerIsResponsible();
}
[ServiceContract]
public interface IMyCallbackContract
{
[OperationContract]
void NewMessageToClient(string msg);
[OperationContract]
void ClientIsResponsible();
}
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
ServiceMetadataBehavior behavior = new
ServiceMetadataBehavior();
//behavior.HttpGetEnabled = true;
//behavior.
ServiceHost serviceHost = new
ServiceHost(
typeof(MyService),
new Uri("net.tcp://localhost:8080/"));
serviceHost.Description.Behaviors.Add(behavior);
serviceHost.AddServiceEndpoint(
typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexTcpBinding(),
"mex");
serviceHost.AddServiceEndpoint(
typeof(IMyService),
new NetTcpBinding(),
"ServiceEndpoint");
serviceHost.Open();
MessageBox.Show(
"server is up");
// label1.Content = label1.Content + String.Format(" net.tcp://localhost:8080/");
}
}
public class MyService : IMyService
{
public void NewMessageToServer(string msg)
{
}
public bool ServerIsResponsible()
{
return true;
}
}
}
I am getting a Xaml parse exception in Line 1, what can be the problem?
Thanks!
Your Window1 constructor is throwing an exception. Confusingly, WPF wraps such exceptions in a XamlParseException, even though they have nothing to do with XAML.
To find out what is going on:
Break on the exception and bring up the exception assistant.
Open the details.
Look at the InnerException. This will be a TargetInvocationException.
Expand the InnerException and look at its InnerException.
This "inner inner exception" is the exception that was thrown in your constructor. Look at the type and message of the exception, and go from there.
I wrote a few tips on debugging XamlParseExceptions here.
often I get a XAML parse exception when something in the constructor or even the program launch fails. Though the XAML is correct, the runtime can not construct all necessary objects to start the XAML up and throws this error.
Have a look at the exception: Any inner exceptions that might show another error?
If this doesn't help, debug step by step. But without any further help, this is hard to tackle.
-sa

Resources