【发布时间】:2010-11-06 16:27:20
【问题描述】:
以下代码隐藏绑定适用于 SmartFormView 用户控件:
查看:
<UserControl x:Class="CodeGenerator.Views.PageItemManageSettingsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:v="clr-namespace:CodeGenerator.Views"
xmlns:vm="clr-namespace:CodeGenerator.ViewModels"
Background="#ddd">
<Grid Margin="10">
<ScrollViewer DockPanel.Dock="Top">
<StackPanel Margin="10">
<v:SmartFormView/>
</StackPanel>
</ScrollViewer>
</Grid>
</UserControl>
代码隐藏:
using System.Windows.Controls;
using CodeGenerator.ViewModels;
namespace CodeGenerator.Views
{
public partial class SmartFormView : UserControl
{
public SmartFormView()
{
InitializeComponent();
DataContext = new SmartFormViewModel("testing");
}
}
}
但是,我想在调用视图的 ViewModel 中将 SmartFormView 绑定到其 SmartFormViewModel,而不是在代码隐藏中硬编码。然而这两种方法并不绑定:
<UserControl.Resources>
<DataTemplate DataType="{x:Type vm:SmartFormViewModel}">
<v:SmartFormView/>
</DataTemplate>
</UserControl.Resources>
...
<Grid Margin="10">
<ScrollViewer DockPanel.Dock="Top">
<StackPanel Margin="10">
<TextBlock Text="{Binding Testing}"/>
<v:SmartFormView DataContext="{Binding SmartFormViewModel}"/>
<ContentControl Content="{Binding SmartFormViewModel}"/>
</StackPanel>
</ScrollViewer>
</Grid>
在 ViewModel 中,我将“Testing”和“SmartFormViewModel”定义为 ViewModel 属性并填充它们(如下所示),但是虽然 Testing 属性绑定得很好,但 SmartFormView 不绑定到它的 SmartFormViewModel:
private SmartFormViewModel _smartFormViewModel=;
public SmartFormViewModel SmartFormViewModel
{
get
{
return _smartFormViewModel;
}
set
{
_smartFormViewModel = value;
OnPropertyChanged("SmartFormViewModel");
}
}
private string _testing;
public string Testing
{
get
{
return _testing;
}
set
{
_testing = value;
OnPropertyChanged("Testing");
}
}
public PageItemManageSettingsViewModel(MainViewModel mainViewModel, PageItem pageItem)
: base(mainViewModel, pageItem)
{
SmartFormViewModel SmartFormViewModel = new SmartFormViewModel("manageSettingsMain");
Testing = "test ok";
}
将 XAML 中的 UserControl 绑定到调用 View 的 ViewModel 中的特定 ViewModel 的语法是什么?
【问题讨论】: