我有一个带有ViewModel'ViewModelA'的UserControl'UserControlA'。 'UserControlA'有'UserControlB','UserControlB'有'ViewModelB'。
当我将'UserControlA'中的DependencyProperty与'ViewModelA'属性绑定时, 没有一个被解雇的人。
Belows是代码,
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>
ViewA.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);
}
}
请帮我解决这个问题。
答案 0 :(得分:1)
该行
Socks: 30, 10, 30, 40, 30, 50, 40, 60, 70
Pair: (30, 30)
Pair: (40, 40)
Rest: 10, 30, 50, 60, 70
是多余的,因为DataContext被隐式用作Binding的源对象。
但是,在执行UserControl的构造函数期间,typeBinding.Source = this.DataContext;
属性尚未设置(即它为DataContext
),因此您有效地将Binding的null
属性设置为{{ 1}}。只需删除该行,或写入
Source