I have a pretty simple requirement where a UserControl needs to offer the user a way to select an item from its droplist. When the user clicks a button, the UserControl will perform some amount of internal tests, then it will call a method in the host application and pass it the user's selection.
I have this working using MVVM, but I'm a little perplexed by what I had to do to make it work. In my experience with databinding, it seems like I still have some gaps in my knowledge because each new implementation seems to get me with problems that I hadn't expected.
My UserControl is simple, it's a droplist and a button:
<UserControl x:Class="MyUserControl.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">
<StackPanel Orientation="Vertical">
<ComboBox ItemsSource="{Binding MyItems}" IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding MySelectedItem}" />
<Button Content="Click me" Command="{Binding ClickMeCommand}" />
</StackPanel>
</UserControl>
The code behind looks like this and just sets up the data for the controls:
using GalaSoft.MvvmLight.CommandWpf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MyUserControl
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public ICollectionView MyItems { get; set; }
public RelayCommand ClickMeCommand { get; set; }
public string MySelectedItem { get; set; }
public ICommand HostClickMeCommand
{
get { return (ICommand)GetValue(HostClickMeCommandProperty); }
set { SetValue(HostClickMeCommandProperty, value); }
}
// Using a DependencyProperty as the backing store for HostClickMeCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HostClickMeCommandProperty =
DependencyProperty.Register("HostClickMeCommand", typeof(ICommand), typeof(UserControl1), new PropertyMetadata(null));
public UserControl1()
{
InitializeComponent();
DataContext = this;
MyItems = CollectionViewSource.GetDefaultView( new List<string> { "John", "Mary", "Joe" });
ClickMeCommand = new RelayCommand( ExecuteClickMeCommand);
}
private void ExecuteClickMeCommand()
{
MessageBox.Show( "Hello from user control!");
if( HostClickMeCommand != null) {
HostClickMeCommand.Execute( MySelectedItem);
}
}
}
}
You'll notice that the button click handler for my UserControl will display a message, then call into my application.
The application's XAML is also very easy:
<Window x:Class="MyHostApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uc="clr-namespace:MyUserControl;assembly=MyUserControl"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<uc:UserControl1 HostClickMeCommand="{Binding MyHostClickMeCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</DockPanel>
</Window>
As is its code-behind:
using GalaSoft.MvvmLight.CommandWpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MyHostApplication {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public RelayCommand<string> MyHostClickMeCommand { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
MyHostClickMeCommand = new RelayCommand<string>( (name) => { MessageBox.Show( String.Format( "Hello from host, {0}!", name)); });
}
}
}
This code works fine.
But my question is: Why do I have to have the RelativeSource specified in my binding? Since the DataContext for the application window is itself, why won't the Window bind UserControl's dependency property to MyHostClickMeCommand? If I remove the RelativeSource, the application's handler is not called.
I should also add that the reason why I want to figure out the proper way to define the binding is because I want to be able to set the ViewModel of my application to a different class. Ideally, I'd like my application to have this in the XAML:
<Window.DataContext>
<local:MainViewModel />
</Window.DataContext>
where MainViewModel is in the ViewModels folder in my application's project file.