【问题标题】:Binding viewmodel to view has usercontrol with own viewmodel将视图模型绑定到视图具有用户控件和自己的视图模型
【发布时间】:2016-11-02 07:38:48
【问题描述】:

我有一个带有 ViewModel 'ViewModelA' 的 UserControl 'UserControlA'。 “UserControlA”有“UserControlB”,“UserControlB”有“ViewModelB”。

当我将“UserControlA”中的 DependencyProperty 与“ViewModelA”属性绑定时, 没有任何 setter 被解雇。

以下是代码,

ViewA.xaml

<UserControl
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:vm="clr-namespace:MyTest.ViewModel
         xmlns:custom="clr-namespace:MyTest.Views
         x:Name="userControl" x:Class="MyTest.Views.UserControlA"             
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="500">

<UserControl.DataContext>
    <vm:UserViewModel x:Name="uvModel"/>
</UserControl.DataContext>
<Grid>
<custom:UserControlB></custom:UserControlB>

查看A.cs

public partial class UserView : UserControl, IUserView
{        
    static DependencyProperty UserTypeProperty = DependencyProperty.Register("UserType", typeof(UserType), typeof(UserView), new PropertyMetadata(UserType.None));
    public UserType UserType { get { return (UserType)GetValue(UserTypeProperty); } set { SetValue(UserTypeProperty, value); } }
    public ViewA()
    {
        InitializeComponent();

        Binding typeBinding = new Binding();
        typeBinding.Source = this.DataContext;
        typeBinding.Path = new PropertyPath("User.UserType");
        typeBinding.Mode = BindingMode.OneWayToSource;
        this.SetBinding(UserTypeProperty, typeBinding);           
    }

ViewModelA.cs

public class ViewModelA : ViewModelBase
{

    User user = new User();
    public User User
    {
        get { return this.user; }
        set
        {
            this.user = value;                
            RaisePropertyChanged(() => User);                
        }
    }

请帮我解决这个问题。

【问题讨论】:

  • 这里似乎有一堆错误,但不确定是否是由于编辑问题造成的。您的 DP 定义缺少 getter/setter,您声称 has usercontrol with own viewmodel 但我在您的代码中没有看到(可怕的代码气味),而且我无法判断您的 ViewModelA 是否具有公共属性 ViewModelB,如果您的UserControlB 嵌套在您的 ViewModelA 中。
  • 哦,对不起。我更新了问题并添加了一些代码。

标签: wpf mvvm binding


【解决方案1】:

线

typeBinding.Source = this.DataContext;

是多余的,因为 DataContext 被隐式用作 Binding 的源对象。

但是,在执行 UserControl 的构造函数期间,尚未设置 DataContext 属性(即它是 null),因此您实际上是将 Binding 的 Source 属性设置为 null。只需删除该行,或编写

SetBinding(UserTypeProperty, new Binding
{
    Path = new PropertyPath("User.UserType"),
    Mode = BindingMode.OneWayToSource
}); 

【讨论】:

    猜你喜欢
    • 2010-11-06
    • 2011-02-22
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    相关资源
    最近更新 更多