mahboub_mo
mahboub_mo

Reputation: 3038

How to Bind a button in a DataTemplate to a ViewModel?

I have a DataTemplate that have put in a ResourceDictionary, and there is a button in the DataTemplate and I put this DataTemplate in a window. Now I want to bind the Button Command to a property of windowViewModel,how can I do that? this is the code:

 <DataTemplate DataType="{x:Type types:User}" x:Key="UserTemp">
    <Grid  >
        <Button  Command="{Binding  RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ????}, AncestorLevel=1}, Path=SelectLocationCommand}" />
    </Grid>
</DataTemplate>

and in Window.xaml

<ContentControl x:Name="UserTemp" />

and in WindowViewModel:

  public ICommand SelectLocationCommand
    {
        get {return new RelayCommand(selectLocationCommand); }
    }
    void selectLocationCommand()
    {
        _welcomeTitle = "AA";
    }

Upvotes: 1

Views: 692

Answers (1)

AlexDrenea
AlexDrenea

Reputation: 8039

The short answer is that you don't need to do it in code.

You defined your DataTemplate as a template for a "User" object. This means that this is how a User object should be shown in the UI. So, in order to use your DataTemplate you should have a "User" instance in your WindowViewModel. This means that the SelectLocationCommand should be in the User object and not in the WindowViewModel.

Having said all that, your code should look somthing like this:

In Window.xaml

<ContentControl Content="{Binding User}" ContentTemplate="{StaticResource UserTemp}" />

In WindowViewModel

public User User {get;set}

In User

public ICommand SelectLocationCommand
{
    get {return new RelayCommand(selectLocationCommand); }
}
void selectLocationCommand()
{
    _welcomeTitle = "AA";
}

Also, make sure that the Window.xaml's DataContext is WindowViewModel. There's a number of better ways to do this but the easiest would be:

In Window.xaml.cs

public MainWindow()
{
    InitializeComponent();
    this.DataContext = new WindowViewModel();
}

Upvotes: 2

Related Questions