【发布时间】:2011-12-16 12:19:16
【问题描述】:
我正在使用 WPF、MVVM 和 PRISM。 我的视图中有一个数据模板链接到 ViewModel UC2002_RFPBeheren_ViewModel,因为包含此代码的页面链接到另一个 ViewModel,我希望 Button 将 UC2002_RFPBeheren_ViewModel 作为 ViewModel。
此页面的数据上下文是 UC2002_RFPBeheren_ProjectInfo_ViewModel 但我希望 SaveButton 使用 ViewModel UC2002_RFPBeheren_ViewModel
这是我的代码:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../Resources/RFPModuleResources.xaml" />
<ResourceDictionary>
<DataTemplate x:Key="SaveButton" DataType="{x:Type vm:UC2002_RFPBeheren_ViewModel}">
<Button Command="{Binding SaveRFPCommand}">Save</Button>
</DataTemplate>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
<ContentControl ContentTemplate="{StaticResource SaveButton}"/>
<Button Command="{Binding CloseTabCommand}">Close</Button>
</StackPanel>
虽然 SaveButton 显示但不响应我的命令。
我忘记了什么还是有其他方法可以解决这个问题?
提前致谢;)!
================================================ ===================================
编辑:
所以我做了一些更改,但它仍然不起作用。
代码示例:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../Resources/RFPModuleResources.xaml" />
<ResourceDictionary>
<DataTemplate x:Key="SaveButton" DataType="{x:Type vm:UC2002_RFPBeheren_ViewModel}">
<Button Command="{Binding SaveRFPCommand}">Save</Button>
</DataTemplate>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
我在页面的ViewModel中设置了这个属性
public UC2002_RFPBeheren_ViewModel MySaveVM { get; set; }
我的堆栈面板现在看起来像这样:
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
<ContentControl Content="{Binding MySaveVM}" ContentTemplate="{StaticResource SaveButton}"/>
<Button Command="{Binding CloseTabCommand}">Close</Button>
</StackPanel>
【问题讨论】:
-
所以要清楚。你曾经设置过你的视图的 DataContext 吗?即 DataContext 是否设置为 UC2002_RFPBeheren_ViewModel 的实例?
-
页面是一个用户控件,一个tabitem,datacontext是用这个代码设置的:
-
因此,如果 DataContext 是您的 ViewModel,那么我在您将 ContentControl 的内容设置为“{Binding}”的位置给出的答案应该可以工作。
-
我不希望页面的主要数据上下文成为按钮的数据上下文。我想要按钮上的差异数据上下文而不是主按钮。
-
所以上面StackPanel的DataContext是UC2002_RFPBeheren_ProjectInfo_ViewModel。并且大概具有 CloseTabCommand 属性,因为这是您将 Button 兄弟绑定到相关 ContentControl 的内容。在您用于 ContentControl 的模板中,您将绑定到名为 SaveRFPCommand 的属性。什么对象定义了该属性?如果这也在 UC2002_RFPBeheren_ProjectInfo_ViewModel 上,那么您确实希望将其用作 DataContext。如果那不在其上的子对象上,那么您将绑定到返回该子对象的属性。