开发者

MVVM Multiple Bindings Problem

开发者 https://www.devze.com 2023-04-06 17:46 出处:网络
I have the following XAML layout <DataTemplate x:Key=\"Reports\"> <Grid> <Grid.ColumnDefinitions>

I have the following XAML layout

<DataTemplate x:Key="Reports">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding Title}" Grid.Column="1"/>
            <telerik:RadButton x:Name="Edit" 
                               Command={Binding MyCommand} <!-- From View Model -->
                               CommandParameter={Binding Id}/> <!-- From DataTemplate -->
        </Grid>

    </DataTemplate>

I would like to bind a command to the button which would require me to set the data context of the button to the ViewModel.

But I would like to bind data from the DataTemplate data context to the command parameter.

Is is possible to have two data contexts within th开发者_如何学Ce same control?


No, it's not. But you can associate the binding to a command in your viewmodel:

<telerik:RadButton x:Name="Edit" 
    Command="{Binding DataContext.MyCommand, ElementName=Root}" <!-- From View Model -->
    CommandParameter="{Binding Id}"/> <!-- From DataTemplate -->

Here "Root" is the name of the user control or page where you are using this code:

<UserControl x:Name="Root" ...

This page would be bound to your view model, so you can use the DataContext to access it. That's why you use the path DataContext.MyCommand in the binding. Finally, in your viewmodel, you should have the command:

public ICommand MyCommand
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号