I have a MainWindow containing a UserControl, both implemented in an MVVM sample. MainWindowVM has properties that I want to bind to properties in UserControl1VM. But that does not work.
Here is some code (viewmodels use some kind of mvvm-framework that implement INotifyPropertyChanged in the ViewModelBase class, but hopefully not a 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 is 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>
Codebehind UserControl1.xaml.cs:
using System.Windows.Controls; namespace DPandMVVM {
And 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, DP cannot be found in MainWindow.xaml.
What am I doing wrong?