如何将此View绑定到此ViewModel?

时间:2009-06-29 12:54:35

标签: c# wpf xaml binding mvvm

以下代码隐藏绑定适用于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绑定到调用View的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";
}

将XAML中的UserControl绑定到调用View的ViewModel中的特定ViewModel的语法是什么?

1 个答案:

答案 0 :(得分:6)

可能是错的,但我认为你的代码中只有一个错误。

SmartFormViewModel SmartFormViewModel = new SmartFormViewModel("manageSettingsMain");

应该是:

SmartFormViewModel = new SmartFormViewModel("manageSettingsMain");

即。您的SmartFormViewModel 永远不会被设置。因此,您在父视图中的绑定找不到它。

除此之外,更好的方法是将您的孩子VM粘贴到可视树中:

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

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