Xaml parse exception is thrown when i define a duplex contract - wpf

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

Related

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

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.

How to make a second project in the same solution for Windows Phone/Wpf/Windows type of solution

I have a Windows Phone project and my business demands to create another one with some slight changes in the front-end (XAML). How to create another project that is identical to the first one but only the XAML files are different? I don't use MVVM. What I tried is creating a new project and copy the XAML files from the first one, and then LINK all other CS files, but it became a mess with all these namespaces and stuff.. I have resource dicionaries and lots of dependencies in the code. Any ideas how to make such a project that shares the same code-behind files with some differences in Visual Studio?
XAML with a code behind are partial classes. You cannot have two partial classes referring to the same class in two different assemblies. Therefore I think you can't use common code behind for XAML from different projects.
The best approach is using a common view model for different views, but you don't use MVVM pattern.
Then you can use something like a proxy. The proxy is a common class in a separate assembly. It contains all logic and data.
You get or set any state from your code behind only by the proxy.
UPD: Example:
It's a common contract for each view (it's an interface from a common assembly):
public interface IMyWindow
{
Label HelloLabel { get; }
}
It's the first WPF project:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="First Application" Height="350" Width="525">
<StackPanel>
<Label x:Name="_helloLabel" Content ="Hello, I'm First Application!"></Label>
<Button Click="ButtonBase_OnClick" Height="100">Press me</Button>
</StackPanel>
</Window>
public partial class MainWindow : Window, IMyWindow
{
private readonly MyWindowProxy _proxy;
public MainWindow()
{
InitializeComponent();
_proxy = new MyWindowProxy(this);
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
_proxy.OnButtonClick();
}
public Label HelloLabel
{
get { return _helloLabel; }
}
}
It's the second WPF project:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Second Application" Height="350" Width="525">
<StackPanel>
<Label x:Name="_helloLabel" Content ="Hello, I'm Second Application!"></Label>
<Button Click="ButtonBase_OnClick" Width ="50" Height="50">OK</Button>
</StackPanel>
</Window>
public partial class MainWindow : Window, IMyWindow
{
private readonly MyWindowProxy _proxy;
public MainWindow()
{
InitializeComponent();
_proxy = new MyWindowProxy(this);
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
_proxy.OnButtonClick();
}
public Label HelloLabel
{
get { return _helloLabel; }
}
}
It's a proxy for each view (it's a class from a common assembly):
public class MyWindowProxy
{
private readonly IMyWindow _window;
public MyWindowProxy(IMyWindow window)
{
_window = window;
}
public void OnButtonClick()
{
_window.HelloLabel.Content = "Hello from common proxy!";
}
}
Once again, this is NOT the best way to build an application architecture. I highly recommend using MVVM pattern then the question of separating of business logic disappear by itself.

why this is correct in mvvm pattern and the messageBox isnt? I don't see the difference (MVVM Light)

I found a small example that uses MVVM Light to show a message to the user. How it uses MVVM Light, I guess, is that it respects the MVVM pattern.
The view code behind:
namespace DialogosPruebas
{
/// <summary>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Messenger.Default.Register<DialogMessage>(
this,
msg =>
{
var result = MessageBox.Show(
msg.Content,
msg.Caption,
msg.Button);
// Send callback
msg.ProcessCallback(result);
});
}
}
}
And the ViewModel is:
using System;
using System.Windows;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
namespace DialogosPruebas.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase
{
private const string Login = "abcd1234";
public RelayCommand<string> CheckLoginCommand
{
get;
private set;
}
/// <summary>
/// The <see cref="Message" /> property's name.
/// </summary>
public const string MessagePropertyName = "Message";
private string _message = "Login";
/// <summary>
/// Gets the Message property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public string Message
{
get
{
return _message;
}
set
{
if (_message == value)
{
return;
}
_message = value;
RaisePropertyChanged(MessagePropertyName);
}
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
CheckLoginCommand = new RelayCommand<string>(CheckLogin);
}
private void CheckLogin(string text)
{
if (text == Login)
{
var message = new DialogMessage("Login confirmed, do you want to continue", DialogMessageCallback)
{
Button = MessageBoxButton.OKCancel,
Caption = "Continue?"
};
Messenger.Default.Send(message);
}
}
private void DialogMessageCallback(MessageBoxResult result)
{
if (result == MessageBoxResult.OK)
{
Message = "Continue";
}
else
{
Message = "Stop";
}
}
}
}
The AXML:
<Window x:Class="DialogosPruebas.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<Binding Path="Main" Source="{StaticResource Locator}"/>
</Window.DataContext>
<Grid>
<StackPanel x:Name="LayoutRoot" Background="Black">
<TextBlock FontSize="36"
FontWeight="Bold"
Foreground="Purple"
Text="{Binding Message}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextWrapping="Wrap" Margin="0,10" />
<TextBox x:Name="LoginTextBox" TextWrapping="Wrap" Margin="10,0" FontSize="21.333" Text="Enter login">
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyUp">
<cmd:EventToCommand Command="{Binding CheckLoginCommand, Mode=OneWay}" CommandParameter="{Binding Text, ElementName=LoginTextBox}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
<TextBlock TextWrapping="Wrap" Text="(Enter abcd1234 to trigger the message)" HorizontalAlignment="Center" Margin="0,10,0,0" FontSize="16" Foreground="White"/>
</StackPanel>
</Grid>
</Window>
Well, my doubt is, in the code behind the view we use MessageBox and the ViewModel has this code:
var message = new DialogMessage("Login confirmed, do you want to continue", DialogMessageCallback)
{
Button = MessageBoxButton.OKCancel,
Caption = "Continue?"
};
Messenger.Default.Send(message);
This sends a request to the view, to the code behind, that then uses MessageBox.
Why is this better than this solution, which uses MessageBox in the ViewModel directly, like this:
private void CheckLogin(string text)
{
if (text == Login)
{
MessageBox.Show("Login correct");
}
}
?
What is the difference? In both cases I use MessageBox and I have to wait for the user's response.
I have read that to use MessageBox in the viewModel is not a good idea, but I don't see what the difference is in this case.
I see two reasons why this approach might be desirable:
1 - Your ViewModels need to be Unit Tested.
raising modal dialogs such as a MessageBox leads to all sorts of problems in Unit Tests. The decoupled Messenger approach is safe because in a Unit Test, either no one is listening to the messages, or there is a mocked listener that just returns "Yes" for all user-facing prompts.
2 - Your ViewModels are supposed to be reused on other platforms.
Don't worry about this too much if you're targeting Windows (WPF) only.
The main concern that leads to complete separation from UI is if you will reuse your ViewModels in other platforms.
For example, there's no MessageBox.Show() in Android, therefore, if you intend to reuse your ViewModel's "Application Logic" there you will need to abstract that code away and provide platform-specific code on each case.
If none of these are important for you, then IMO it's perfectly fine to raise MessageBoxes in your ViewModels, as well as other View-specific issues (such as Window closing) which might be overly complex given the abstractions required by MVVM, for no gain.
The difference is that by sending a message (DialogMessage) your ViewModel is asking the View to show a message. How the message is actually displayed depends on the View. In this case the View will show a simple MessageBox but it could use a UserControl to show a custom dialog.
Using a message the ViewModel doesn't need to know how the message will be displayed so it's still decoupled from the View.

How to lock the orientation of WPF application

Is there an API to lock the orientation of my WPF application to run only in the landscape mode.
i could find event that could fire on orientation change, but is there a way to lock it
Microsoft.Win32.SystemEvents.DisplaySettingsChanged
I dont think there is a way in WPF to lock it, you could provide a rotation layout transformation to the root container. It is not actually locking the orientation but rotating your application. Something like this,
<Grid.RenderTransform>
<RotateTransform Angle="-90"/>
</Grid.RenderTransform>
Read here,
Layout Transformation
For anyone who arrives at this question and is left needing more detail, here is a fully detailed answer...
It appears that as tablet rotation support was done at the individual vendor level, there isn’t much support for it in Windows 7 / 8 other than detecting that there was a change in rotation. The screen can still be pseudo-locked into a landscape format with a bit of XAML sleight of hand. Here’s some sample code that I knocked up last night and tested on my tablet PC…
MainWindow.xaml
<Window x:Class="LockRotationWpf.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:LockRotationWpf"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid HorizontalAlignment="Center"
VerticalAlignment="Center"
RenderTransformOrigin="0.5,0.5" >
<Grid.RenderTransform >
<RotateTransform Angle="{Binding Angle}" />
</Grid.RenderTransform>
<StackPanel>
<TextBlock FontSize="100" Text="Landscape"/>
<TextBlock Text="{Binding Angle}" TextAlignment="Center"/>
</StackPanel>
</Grid>
</Window>
MainWindow.xaml.cs
using System.Windows;
using LockRotationWpf.ViewModels;
namespace LockRotationWpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var vm = new MainWindowViewModel();
DataContext = vm;
}
}
}
ViewModels\MainWindowViewModel.cs
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using LockRotationWpf.Annotations;
namespace LockRotationWpf.ViewModels
{
// Omit the INotifyPropertyChanged implementation if already implemented on a base ViewModel class.
public class MainWindowViewModel : INotifyPropertyChanged
{
public double _angle;
public MainWindowViewModel()
{
Microsoft.Win32.SystemEvents.DisplaySettingsChanged += DisplaySettingsChanged;
}
private void DisplaySettingsChanged(object sender, EventArgs e)
{
Angle = System.Windows.SystemParameters.PrimaryScreenHeight > System.Windows.SystemParameters.PrimaryScreenWidth ? -90 : 0;
}
public double Angle
{
get { return _angle; }
set
{
_angle = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Here are a couple of screen-shots that show the change in orientation. If you’re running an App full screen you won’t get the window chrome and you’d be unaware that the screen had actually rotated. Any on-screen keyboard which opens in response to a text input will of course still pop-up in the portrait position, but the fact that the content is always landscape should give the operator enough of a hint to turn the tablet around for input.
I hope that helps anyone who lands here.
This worked for me
[System.Runtime.InteropServices.DllImport("user32", EntryPoint = "SetDisplayAutoRotationPreferences")]
private static extern UInt32 SetDisplayAutoRotationPreferences8(UInt32 orientation);
[System.Runtime.InteropServices.DllImport("kernel", EntryPoint = "SetDisplayAutoRotationPreferences")]
private static extern UInt32 SetDisplayAutoRotationPreferences7(UInt32 orientation);
public MyWindow()
{
InitializeComponent();
}
And on load of my main window :
SetDisplayAutoRotationPreferences8(2);//Lanscape

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.

Resources