【问题标题】:MVVM Multiple Bindings ProblemMVVM 多重绑定问题
【发布时间】:2011-09-20 15:56:16
【问题描述】:

我有以下 XAML 布局

<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>

我想将命令绑定到按钮,这需要我将按钮的数据上下文设置为 ViewModel。

但我想将 DataTemplate 数据上下文中的数据绑定到命令参数。

在同一个控件中是否可以有两个数据上下文?

【问题讨论】:

    标签: silverlight binding mvvm-light


    【解决方案1】:

    不,不是。但是您可以将绑定与视图模型中的命令相关联:

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

    这里的“根”是您使用此代码的用户控件或页面的名称:

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

    此页面将绑定到您的视图模型,因此您可以使用 DataContext 访问它。这就是您在绑定中使用路径DataContext.MyCommand 的原因。 最后,在您的视图模型中,您应该有以下命令:

    public ICommand MyCommand
    

    【讨论】:

    • 感谢您的回复,我正在努力理解如何使用您发布的代码,请您详细说明一下。谢谢。
    • 我稍微扩展了答案。让我知道现在是否更清楚:)
    猜你喜欢
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多