如何将此视图绑定到此视图模型?

6
以下代码后台绑定适用于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绑定到调用视图的ViewModel中的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";
}

在调用视图的ViewModel中,将UserControl在XAML中绑定到特定的ViewModel的语法是什么?
1个回答

6
可能有些不对,但我认为你的代码中有一个错误。
SmartFormViewModel SmartFormViewModel = new SmartFormViewModel("manageSettingsMain");

应该是:

SmartFormViewModel = new SmartFormViewModel("manageSettingsMain");

例如:您的SmartFormViewModel从未被设置。因此,您在父视图中绑定的内容找不到它。

此外,更好的方法只是将子VM插入可视树中:

<ContentControl Content="{Binding SmartFormViewModel}"/>

使用DataTemplate来解析视图,而不是将视图“硬编码”到父视图中。


是的,就是这样,感谢你找到了那个问题,很高兴看到这个。好的,我也尝试了你提供的第二种方法,也很有效,而且对我来说更有意义。所以你似乎是“定义空区域”,然后通过ViewModel动态填充它们,在渲染时自动绑定到它们相应的DataTemplates,这很合理,不错,谢谢! - Edward Tanguay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接