【发布时间】: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 中。 -
哦,对不起。我更新了问题并添加了一些代码。