I have been learning MVVM / WPF and have gone through the tutorial here.
I have created a working application using this methodology but now, on a new project, I cannot get the Dependency Injection to work.
When I run this project I get an empty MainWindow without the CompanyView injected. I have double and tripled checked everything between the project that works and this one that doesn't and cannot find the reason for CompanyView not being injected. I have also tried cleaning the solution and restarting VS to no avail. Hopefully someone can see what I am missing.
I have the following file:
App.xaml.cs (using base.OnStartup() instead of StartupUri in App.xaml)
namespace SidekickAdmin
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow window = new MainWindow();
var viewModel = new MainWindowViewModel();
window.DataContext = viewModel;
window.Show();
}
}
}
MainWindowViewModel.cs
namespace SidekickAdmin.ViewModel
{
class MainWindowViewModel : ViewModelBase
{
public MainWindowViewModel()
{
CompanyViewModel companyViewModel = new CompanyViewModel(_repository);
this.ViewModels.Add(companyViewModel);
}
ObservableCollection<ViewModelBase> _viewModels;
ObservableCollection<ViewModelBase> ViewModels
{
get
{
if (_viewModels == null)
{
_viewModels = new ObservableCollection<ViewModelBase>();
}
return _viewModels;
}
}
}
}
MainWindowView.xaml
<Window x:Class="SidekickAdmin.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:SidekickAdmin.ViewModel"
xmlns:vw="clr-namespace:SidekickAdmin.View"
Title="Sidekick Admin" SizeToContent="WidthAndHeight">
<!-- Typically done in a resources dictionary -->
<Window.Resources>
<ResourceDictionary Source="MainWindowResources.xaml" />
</Window.Resources>
<StackPanel>
<ItemsControl ItemsSource="{Binding ViewModel}" Margin="3" />
</StackPanel>
</Window>
MainWindowResources.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:SidekickAdmin.ViewModel"
xmlns:vw="clr-namespace:SidekickAdmin.View">
<DataTemplate DataType="{x:Type vm:CompanyViewModel}">
<vw:CompanyView />
</DataTemplate>
</ResourceDictionary>
CompanyViewModel.cs (not really used yet as I am still trying to just get the view to appear)
namespace SidekickAdmin.ViewModel
{
class CompanyViewModel : ViewModelBase
{
readonly GenericRepository _repository;
#region Getters & Setters
public ObservableCollection<Company> AllCompanies
{
get;
private set;
}
#endregion
#region Constructors
public CompanyViewModel(GenericRepository repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
_repository = repository;
this.AllCompanies = new ObservableCollection<Company>(_repository.GetAll<Company>());
}
#endregion
protected override void OnDispose()
{
this.AllCompanies.Clear();
}
}
}
CompanyView.xaml
<UserControl x:Class="SidekickAdmin.View.CompanyView"
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"
Height="300" Width="300">
<StackPanel>
<TextBlock>You say Hello</TextBlock>
<TextBlock>And I say Goodbye</TextBlock>
<TextBlock>Hello, Hello</TextBlock>
</StackPanel>
</UserControl>
Lester's comment is right... you are binding to a ViewModel property which does not exist - MainWindowViewModel has a ViewModels property though. The s is important
Besides what #Robert Levy has wrote, the error you are making is that your ViewModels property is private, make it public and it should work fine.
#RobertLevy and #dmusial are correct. You need to make your reference to ViewModels in your XAML plural, to match the property name in your C# code. Also, the property should be public, so the View can see it.
Related
I've dumbed down the code as much as I could to try and get a working piece of code yet I'm still coming up short. Some advice would be appreciated.
I'm trying to get a DependencyProperty working, it's that simple and yet the data I'm setting on the main window isn't showing up in the user control.
In the MainWindow I'm setting the TextValue to "hi" in the xaml. TextValue is showing in the xaml up and compiling just fine so I'm pretty sure I have the DependencyProperty set right. Once the dialog is fully open I take a look in the debugger and my property TextValue is still null.
Am I missing setting the data context? Maybe I'm off base in what I'm looking to do.
Thanks for taking the time to figure out what I'm doing wrong.
My User Control is: UserControl1
Xaml:
<UserControl x:Class="WpfApplication1.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"
Loaded="UserControl_Loaded"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
</Grid>
</UserControl>
UserControl1.xaml.cs is:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("TextValue", typeof(string), typeof(UserControl1));
private string _tv;
public string TextValue
{
get
{
return _tv;
}
set
{
_tv = value;
}
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
}
}
}
My calling window xaml is:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:usercontrols="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525"
Loaded='Window_Loaded'>
<Grid>
<usercontrols:UserControl1 x:Name="usercontroltest1" TextValue="hi"/>
</Grid>
</Window>
My calling window .cs is:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}
}
The getter and setter of the "property wrapper" must call the GetValue and SetValue methods of the DependencyObject base class like shown below. Besides that, there is a naming convention that mandates that a dependency property's identifier field is named like the property plus a Property suffix. See Custom Dependency Properties for all the details.
public static readonly DependencyProperty TextValueProperty =
DependencyProperty.Register(
nameof(TextValue), typeof(string), typeof(UserControl1));
public string TextValue
{
get { return (string)GetValue(TextValueProperty); }
set { SetValue(TextValueProperty, value); }
}
In order to access a UserControl's dependency property in its own XAML, you would typically use a RelativeSource Binding like this:
<UserControl x:Class="WpfApplication1.UserControl1" ...>
<Grid>
<TextBlock Text="{Binding TextValue,
RelativeSource={RelativeSource AncstorType=UserControl}}" />
</Grid>
</UserControl>
I'm trying to get my head around WPF, Unity and MvvMlight (galasoft). So far my little set up works. If I run my application the label is filled with a random name generated by my DataService. (small victory getting all moving parts to work)
But in the design view of Visual Studio the label remains empty. How do i convince VisualStudio to render some 'design time' data in my label?
I'm using: Visual Studio Premium 2013, Unity 4.0.1, MvvmLight 5.2, .net 4.5
App.xaml.cs
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
IUnityContainer container = new UnityContainer();
container.RegisterType<IDataService, DataService>();
container.RegisterType<IMainViewModel, MainViewModel>();
MainWindow mainWindow = container.Resolve<MainWindow>();
mainWindow.Show();
base.OnStartup(e);
}
}
In App.xaml I have not defined the StartUpUri
MainWindow.xaml
<Window x:Class="UnityMvvmTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="500">
<Grid>
<Label x:Name="myLabel" Content="{Binding MyText}"/>
</Grid>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public MainWindow(IMainViewModel theViewModel)
: this()
{
this.DataContext = theViewModel;
}
}
MainViewModel.cs
public class MainViewModel : ViewModelBase, IMainViewModel
{
private readonly IDataService _dataService;
public MainViewModel(IDataService dataService)
{
_dataService = dataService;
if (IsInDesignMode)
{
// Code runs in design time data.
MyText = "Design Data";
}
else
{
// Code runs "for real"
MyText = _dataService.GetName();
}
}
public string MyText { get; set; }
}
I found a method, using hints from https://stackoverflow.com/a/3380895/249845
I created a second (flat) implementation of IMainVieModel in a separate namespace: UnityMvvmTest.ViewModel.Design. This implementation has no logic, it just fills the properties so the designer has some data to display.
This implementation is used in design time, since it is specified as the DesignTime DataContext. (with xmlns:d, xmlns:mc and xmlns:vm). The mc-namespace is needed to hide the d-namespace during runtime, see why.
The result is 5 extra lines in the Xaml, an extra (almost empty) implementation of IMainViewModel. And an extra (empty) constructor in code behind, instead of a constuctor that test for IsInDesignMode. This isn't a big deal, since unity will pick the constructor with the most parameters it can resolve.
MainWindow.xaml
<Window x:Class="UnityMvvmTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:UnityMvvmTest.ViewModel.Design"
d:DataContext="{d:DesignInstance IsDesignTimeCreatable=True, Type=vm:MainViewModel}"
mc:Ignorable="d"
>
<Grid>
<Label x:Name="myLabel" Content="{Binding MyText}" />
</Grid>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
// Contructor used in DesignTime
public MainWindow()
{
InitializeComponent();
}
//Constructor used by Unity
public MainWindow(IMainViewModel theViewModel)
: this()
{
this.DataContext = theViewModel;
}
}
MainViewModel.cs (design time implementation)
namespace UnityMvvmTest.ViewModel.Design
{
public class MainViewModel : IMainViewModel
{
public MainViewModel()
{
MyText = "my Design time data";
}
public string MyText { get; set; }
}
}
I have a WPF application with MVVM that have several pages with common layout e.g. page header and navigation buttons (the middle part of each page is different).
How can I implement the fixed page layout once and extend it in the different pages with MVVM?
In my opinion, the best way to do this is to create a main window or page and then render user controls inside of that using a content control and data templates. Set the content control binding to a property on the main window's view model. You'll need an implementation of INotifyPropertyChanged, of course, then a main window or application view model, some child view models, a content control in your main window or page, then user controls to represent your views...sort of this this:
public abstract class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string property)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if(handler != null)
{
handler(this, new PropertyChangedEventArgs(property));
}
}
[Conditional("DEBUG")]
[DebuggerStepThrough]
protected virtual void VerifyPropertyName(string property)
{
if (TypeDescriptor.GetProperties(this)[property] == null)
{
throw new Exception(property + " property doesn't exist!");
}
}
}
public interface IPageViewModel
{
string Name { get; }
}
public class Page1ViewModel : ObservableObject, IPageViewModel
{
public string Name { get { return "View 1"; } }
}
public class Page2ViewModel : ObservableObject, IPageViewModel
{
public string Name { get { return "View 1"; } }
}
public class ApplicationViewModel : ObservableObject
{
private IPageViewModel currentViewModel;
public IPageViewModel CurrentViewModel
{
get
{
return this.currentViewModel =
this.currentViewModel
?? new Page1ViewModel();
}
set
{
this.currentViewModel = value;
OnPropertyChanged("CurrentViewModel");
}
}
public ApplicationViewModel()
{
this.CurrentViewModel = new Page1ViewModel()
}
}
Your main window or page would have its view model (DataContext) set to an instance of ApplicationViewModel. The content control would then be bound to the CurrentViewModel property of the ApplicationViewModel, like this:
<Window x:Class="WpfScratchApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:WpfScratchApp"
Title="MainWindow" Height="350" Width="525"
DataContext="{DynamicResource AppViewModel}"
>
<Window.Resources>
<ResourceDictionary>
<app:ApplicationViewModel x:Key="AppViewModel" />
</ResourceDictionary>
</Window.Resources>
<Grid>
<!-- Buttons and stuff -->
<ContentControl Content="{Binding CurrentViewModel}" />
</Grid>
</Window>
Then, create UserControl's corresponding to each of those views:
<UserControl x:Class="WpfScratchApp.Views.Page1View"
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="150" d:DesignWidth="150">
<!-- Cool controls and stuff in here... -->
</UserControl>
(Create a similar one corresponding to Page2ViewModel, called "Page2View".) Then, map the view models to the views like this in your app.xaml, or a merged dictionary.
<Application x:Class="WpfScratchApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:views="clr-namespace:PortfolioManager"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<DataTemplate DataType="{x:Type vm:Page1ViewModel}">
<views:Page1View />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:Page2ViewModel}">
<views:Page2View />
</DataTemplate>
</ResourceDictionary>
</Application.Resources>
</Application>
When you change the CurrentViewModel property in the application view model, it should change the value of the binding for the control control. WPF will use the data template corresponding to the type represented by the CurrentViewModel property to render the content.
So, you can have your buttons all set up in the main window and coded to operate on the CurrentViewModel. Then, change out the CurrentViewModel based upon the content you want to show.
I have a MainWindow containing a UserControl, both implemented in MVVM-pattern.
The MainWindowVM has properties that I want to bind to properties in the UserControl1VM. But this doesn't work.
Here's some code (the viewmodels use some kind of mvvm-framework that implement the INotifyPropertyChanged in a ViewModelBase-class but that's hopefully no problem):
MainWindow.xaml:
<Window x:Class="DPandMVVM.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DPandMVVM"
Title="MainWindow" Height="300" Width="300">
<Grid>
<local:UserControl1 TextInControl="{Binding Text}" />
</Grid>
</Window>
CodeBehind MainWindow.xaml.cs:
using System.Windows;
namespace DPandMVVM
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowVM();
}
}
}
MainWindow-ViewModel MainWindowVM.cs:
namespace DPandMVVM
{
public class MainWindowVM : ViewModelBase
{
private string _text;
public string Text { get { return _text; } }
public MainWindowVM()
{
_text = "Text from MainWindowVM";
}
}
}
And here the UserControl1.xaml:
<UserControl x:Class="DPandMVVM.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="300" d:DesignWidth="300">
<Grid>
<TextBlock Text="{Binding TextInTextBlock}" />
</Grid>
</UserControl>
The Codebehind UserControl1.xaml.cs:
using System.Windows.Controls;
namespace DPandMVVM
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
DataContext = new UserControl1VM();
}
}
}
And the Viewmodel UserControl1VM.cs:
using System.Windows;
namespace DPandMVVM
{
public class UserControl1VM : DependencyObject
{
public UserControl1VM()
{
TextInControl = "TextfromUserControl1VM";
}
public string TextInControl
{
get { return (string)GetValue(TextInControlProperty); }
set { SetValue(TextInControlProperty, value); }
}
public static readonly DependencyProperty TextInControlProperty =
DependencyProperty.Register("TextInControl", typeof(string), typeof(UserControl1VM));
}
}
With this constellation the DP cannot be found in MainWindow.xaml.
What am I doing wrong?
First of all you want DependencyProperty TextInControl to be declared inside UserControl1 if you want to bind it from outside.
Move the declaration of DP inside of UserControl1.
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public string TextInControl
{
get { return (string)GetValue(TextInControlProperty); }
set { SetValue(TextInControlProperty, value); }
}
public static readonly DependencyProperty TextInControlProperty =
DependencyProperty.Register("TextInControl", typeof(string),
typeof(UserControl1));
}
Second you have externally set DataContext of UserControl to UserControl1VM,
public UserControl1()
{
InitializeComponent();
DataContext = new UserControl1VM(); <-- HERE (Remove this)
}
So WPF binding engine looking for property Text in UserControl1VM instead of MainWindowVM. Remove setting DataContext and update XAML of UserControl1 to this:
<UserControl x:Class="DPandMVVM.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="300" d:DesignWidth="300"
x:Name="userControl1">
<Grid>
<TextBlock Text="{Binding TextInTextBlock, ElementName=userControl1}" />
</Grid>
</UserControl>
Bind DP using ElementName by setting x:Name on UserControl.
UPDATE
In case you want to have ViewModel intact for UserControl, you have to update binding in MainWindow. Explicitly tell WPF binding engine to look for property in MainWindow's DataContext using ElementName in binding like this:
<local:UserControl1 TextInControl="{Binding DataContext.Text,
ElementName=mainWindow}" />
For this you need to set x:Name="mainWindow" on window root level.
The XAML of your control right now reference the property TextInTextBlock via the DataContext which in turn "Points" to your main window's view model. Reference the data of the control and you are done (btw do not set the DataContext for that reason - the binding won't work any more):
<UserControl x:Class="DPandMVVM.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="300" d:DesignWidth="300"
x:Name="self">
<Grid>
<TextBlock Text="{Binding TextInTextBlock, ElementName=self}" />
</Grid>
</UserControl>
This is how I do UserControls with MVVM and DP binding. It's similar to Rohit's answer but with some slight changes. Basically you need to set the Control's internal view model to be the DataContext of the root container within the UserControl rather than the UserControl itself, that way it will not interfere with DP bindings.
E.g.
UserControl XAML
<UserControl x:Class="DPandMVVM.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="300" d:DesignWidth="300"
x:Name="userControl1">
<Grid x:Name="Root">
<TextBlock Text="{Binding TextFromVM}" />
</Grid>
UserControl Code-behind
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
this.ViewModel = new UserControlVM();
}
public UserControlVM ViewModel
{
get { return this.Root.DataContext as UserControlVM ; }
set { this.Root.DataContext = value; }
}
public string TextFromBinding
{
get { return (string)GetValue(TextFromBindingProperty); }
set { SetValue(TextFromBindingProperty, value); }
}
public static readonly DependencyProperty TextFromBindingProperty =
DependencyProperty.Register("TextFromBinding", typeof(string), typeof(UserControl1), new FrameworkPropertyMetadata(null, OnTextBindingChanged));
private static void OnTextBindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var uc = d as UserControl1;
uc.ViewModel.TextFromVM = e.NewValue as string;
}
}
This means that the control derives it's values from the Root element DataContext which is our ViewModel but the ViewModel can be updated via a DP binding from outside the control (in your case a binding to the parent Window's ViewModel, see below)
Window XAML
<Window x:Class="DPandMVVM.Window1"
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:DPandMVVM"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
x:Name="window1">
<Grid x:Name="Root">
<local:userControl1 TextFromBinding="{Binding TextFromWindowVM}" />
</Grid>
I have a method that I believe is a lot simpler, and probably more true to MVVM.
In the main window XAML:
<myNameSpace:myUserControl DataContext="{Binding Status}"/>
In your main view model (the data context of the main window:
public myUserControlViewModel Status { set; get; }
now you can in the constructor (or whenever you want to instantiate it):
Status = new myUserControlViewModel();
then if you want to set the text property:
Status.Text = "foo";
and make sure you have the binding setup to a property named Text inside your myUserControlViewModel class:
<TextBox Text="{Binding Text}"/>
and make sure the property fires PropertyChanged, of-course.
Plus, if you use Resharper. You can create a Design instance of the UserControl in your XAML so that it can link the bindings and not tell you that the property is never used by doing this:
<UserControl x:Class="myNameSpace.myUserControl"
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:myNameSpace="clr-namespace:myNameSpace"
d:DataContext="{d:DesignInstance myNameSpace.myUserControl}"
mc:Ignorable="d" ...>
This part:
xmlns:myNameSpace="clr-namespace:myNameSpace"
d:DataContext="{d:DesignInstance myNameSpace.myUserControl}"
Here's a possible working solution for you. However, I've noted in a comment above that this will work in code and perhaps (like my situation) will show up as an error (Object Not Found) in the designer:
<local:UserControl1 TextInControl="{Binding DataContext.Text,
Source={x:Reference <<Your control that contains the DataContext here>>}}" />
I'd rather to have a cleaner solution, though, without any designer errors. I wish to find out how to properly bind a dependency property in a user control to a value coming from the window it's contained in. What I'm finding is that whatever I try to do (short of what I showed above), such as using ElementName and/or AncestorType/Level, etc., the debugger complains that it can't find the source and shows that it's looking for the source inside the context of the user control! It's like I can't break out of the user control context when doing Binding logic in the use of that control (other than that "designer-breaking" solution above).
UPDATE:
I noticed that this might not work for you as your situation might force a problem I just noticed if I change my own source to reference the window instead of a control that has the data context. If I reference the window then I end up with a cyclical redundancy. Perhaps you'll figure out a way to use the Source version of the binding that will work okay for you.
I must also add that my situation is probably a bit more complex since my usercontrol is used in the context of a popup.
Im trying to use MVVM on a PRISM Module. I have a ViewModel in my module with a parameterized constructor which accepts an IOutputService object which will be injected using Ninject.
namespace HelloWorld.ViewModels
{
public class HelloWorldViewModel : ViewModelBase
{
private IOutputService outputService;
public HelloWorldViewModel(IOutputService outputService)
{
this.outputService = outputService;
}
}
}
In the HelloWorldModule.cs file, I register IOutputService with a class that implements it.
public class HelloWorldModule : IModule
{
private IKernel kernel;
private IRegionManager regionManager;
public HelloWorldModule(IKernel kernel, IRegionManager regionManager)
{
this.kernel = kernel;
this.regionManager = regionManager;
}
public void Initialize()
{
kernel.Bind<IOutputService>().To<MessageBoxOutputService>();
regionManager.RegisterViewWithRegion("Region1", typeof(HelloWorldView));
}
}
You can also notice that I am registering the HelloWorldView to Region1. HelloWorldView uses HelloWorldViewModel. The problem now is I can't initialize the HelloWorldViewModel in XAML of View because my ViewModel doesn't have a parameterless constructor.
<UserControl x:Class="HelloWorld.Views.HelloWorldView"
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:vm="clr-namespace:HelloWorld.ViewModels"
mc:Ignorable="d">
<UserControl.DataContext>
<vm:HelloWorldViewModel />
</UserControl.DataContext>
<Grid>
</Grid>
</UserControl>
When I run this, the InitializeComponent() method of the View throws an NullReferenceException. Any proper way to make this work? Thanks.
In the codebehind of the view, inject the viewmodel in the constructor.
public partial class HelloWorldView : UserControl
{
public HelloWorldView(HelloWorldViewModel vm)
{
InitializeComponent();
DataContext = vm;
}
}
Well You don't have to set View's DataContext in xaml. It can be simply done in CodeBehind. Add following property to HelloWorldView.xaml.cs
/// <summary>
/// Gets or sets ViewModel.
/// </summary>
[Inject]
public HelloWorldViewModel ViewModel
{
get { return this.DataContext as HelloWorldViewModel; }
set { this.DataContext = value; }
}
When you call RegisterViewWithRegion an instance of that view will be resolved and thanks to InjectAttribute Ninject will provide that View with DataContext. So you don't need to worry about that. Constructor injection should work as well.
Try using ObjectDataProvider.
Example (From MSDN):
<ObjectDataProvider x:Key="myDataSource" ObjectType="{x:Type src:Person}">
<ObjectDataProvider.ConstructorParameters>
<system:String>Joe</system:String>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
Here is a good example by Bea Stollnitz:
Why should I use ObjectDataProvider?