以下代码隐藏绑定(bind)适用于 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");
}
}
}
但是,我想将 SmartFormView 绑定(bind)到它的 SmartFormViewModel 在调用 View 的 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 属性绑定(bind)良好,SmartFormView 不绑定(bind)到它的 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 绑定(bind)到调用 View 的 ViewModel 中的特定 ViewModel 的语法是什么?
最佳答案
可能是错误的,但我认为您的代码中存在错误。
SmartFormViewModel SmartFormViewModel = new SmartFormViewModel("manageSettingsMain");
应该是:
SmartFormViewModel = new SmartFormViewModel("manageSettingsMain");
即。您的 SmartFormViewModel
从未被设置。因此,您在父 View 中的绑定(bind)找不到它。
除此之外,更好的方法是将您的子虚拟机粘贴到可视化树中:
<ContentControl Content="{Binding SmartFormViewModel}"/>
并使用 DataTemplate 来解析 View ,而不是将 View “硬编码”到父 View 中。
关于c# - 如何将此 View 绑定(bind)到此 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1058124/