Q:

Object initializer in XAML

How do XAML object initializers work with CLR properties?
If I need to create a XAML equivalent of :
public MainWindow()
{
    InitializeComponent();

    this.DataContext = new MainWindowViewModel();
}

then it would be :
<Window.DataContext>
    <vm:MainWindowViewModel/>
</Window.DataContext>

But if I want something like this:
public string KeyFieldView { get; set; }

public MainWindow()
{
    InitializeComponent();

    this.DataContext = new MainWindowViewModel()
    {
        KeyFieldVM=KeyFieldView
    };
}

I am able to get till, KeyFieldVM="", but not sure how do I access KeyFieldView.
<Window.DataContext>
    <vm:MainWindowViewModel KeyFieldVM=""/>
</Window.DataContext>

A:

You could bind the KeyFieldVM property provided that it is a dependency property:
public class MainWindowViewModel : DependencyObject
{
    public static readonly DependencyProperty KeyFieldVMProperty =
        DependencyProperty.Register("KeyFieldVM", typeof(string),
            typeof(MainWindowViewModel), new FrameworkPropertyMetadata("ok"));

    public string KeyFieldVM
    {
        get { return (string)GetValue(KeyFieldVMProperty); }
        set { SetValue(KeyFieldVMProperty, value); }
    }
}

<Window ... x:Name="win">
    <Window.DataContext>
        <vm:MainWindowViewModel KeyFieldVM="{Binding KeyFieldView, ElementName=win}"/>
    </Window.DataContext>
    <Grid>
        <TextBlock Text="{Binding KeyFieldVM}" />
    </Grid>
</Window>

This requires the view model to be a DependencyObject though and this has its drawbacks: 
INotifyPropertyChanged vs. DependencyProperty in ViewModel
XAML is markup language. It doesn't have any concept of variables so you cannot do something like this:
<vm:MainWindowViewModel KeyFieldVM="{this.KeyFieldView}"/> <!-- BAD MARKUP -->

If you want to do this you should create the view model programmatically, for example in the code-behind of the view.

