Oliver
Oliver

Reputation: 113

Specify DataContext in code

I have a simple View that I want to bind to my ViewModel. I am currently using the Source= format for the data binding, but would like to convert that into specifying the DataContext in code.

This is what I have and it is working ...

XAML:

   <Window.Resources>
        <local:ViewModel x:Key="ViewModel" />
    </Window.Resources>

    <Button Content="Click">
        <local:EventToCommand.Collection>
            <local:EventToCommandCollection>
                <local:EventToCommand Event="Click" Command="{Binding Source={StaticResource ViewModel}, Path=ClickCommand, diag:PresentationTraceSources.TraceLevel=High}" />
                <local:EventToCommand Event="GotFocus" Command="{Binding Source={StaticResource ViewModel}, Path=GotFocusCommand}" />
            </local:EventToCommandCollection>
        </local:EventToCommand.Collection>
    </Button>
</Window>

ViewModel Code:

public class ViewModel
{
    public Command ClickCommand { get; set; }
    public Command GotFocusCommand { get; set; }

    public ViewModel()
    {
        ClickCommand = new Command((obj) => { Execute(obj); return null; });
        GotFocusCommand = new Command((obj) => { Execute(obj); return null; });
    }

    void Execute(object param)
    {
        if (param != null)
            System.Windows.MessageBox.Show(param.ToString());
        else
            System.Windows.MessageBox.Show("Execute");
    }
}

Now all I want to do is this in my Window's code behind :

public MainWindow()
{
    InitializeComponent();

    DataContext = new ViewModel();
}

and remove the Window.Resources section in XAML, but I can not figure out how I should change my Binding strings accordingly.

Upvotes: 1

Views: 449

Answers (1)

svick
svick

Reputation: 244757

The DataContext is the default Source, so this should work:

<local:EventToCommand Event="GotFocus" Command="{Binding GotFocusCommand}" />

Upvotes: 2

Related Questions