以下代码隐藏绑定适用于SmartFormView用户控件:
View:
<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>
Code-behind:
using System.Windows.Controls;
using CodeGenerator.ViewModels;
namespace CodeGenerator.Views
{
public partial class SmartFormView : UserControl
{
public SmartFormView()
{
InitializeComponent();
DataContext = new SmartFormViewModel("testing");
}
}
}
但是,我想将SmartFormView绑定到调用View的SmartFormViewModel in the ViewModel ,而不是在代码隐藏中硬编码 . 然而,这两种方法并没有结合:
<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 property binds fine , 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";
}
What is the syntax to bind a UserControl in XAML to a specific ViewModel in the calling View's ViewModel?
1 回答
可能是错的,但我认为你的代码中只有一个错误 .
应该:
即 . 您的
SmartFormViewModel
永远不会被设置 . 因此,您在父视图中的绑定找不到它 .除此之外,更好的方法是将您的孩子VM粘贴到可视树中:
并使用DataTemplate来完成视图的分辨率,而不是将视图“硬编码”到母视图中 .