C# 通过XAML绑定将自定义对象传递给UserControl

C# 通过XAML绑定将自定义对象传递给UserControl,c#,wpf,xaml,user-controls,C#,Wpf,Xaml,User Controls,我要做的是创建一个UserControl,我可以向它传递一个Address对象。似乎当我将Address=“{Binding Path=Person.Address}”传递给UserControl时,嵌入的文本框绑定到Text=“{Binding Path=Person.Address}”而不是Text=“{Binding Path=Address.Summary}” 我这样做完全错了吗 如果你想玩这个项目,这里有一个链接: 域对象: namespace WpfApplication2 {

我要做的是创建一个UserControl,我可以向它传递一个Address对象。似乎当我将
Address=“{Binding Path=Person.Address}”传递给UserControl时,嵌入的文本框绑定到
Text=“{Binding Path=Person.Address}”
而不是
Text=“{Binding Path=Address.Summary}”

我这样做完全错了吗

如果你想玩这个项目,这里有一个链接:

域对象:

namespace WpfApplication2
{
    public class Person
    {
        public String Name { get; set; }
        public Address Address { get; set; }
    }

    public class Address
    {
        public String Street { get; set; }
        public String City { get; set; }

        public String Summary { get { return String.Format("{0}, {1}", Street, City); } }
    }
}
主窗口:

namespace WpfApplication2
{
    public partial class MainWindow : Window
    {
        private readonly ViewModel vm;
        public MainWindow()
        {
            InitializeComponent();
            vm = new ViewModel();
            DataContext = vm;

            vm.Person = new Person()
            {
                Name = "Bob",
                Address = new Address()
                {
                    Street = "123 Main Street",
                    City = "Toronto",
                },
            };
        }
    }

    public class ViewModel : INotifyPropertyChanged
    {
        private Person person;
        public Person Person { get { return person; } set { person = value; NotifyPropertyChanged("Person"); } }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication2"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBlock Text="Name:" />
        <TextBlock Text="{Binding Path=Person.Name}" />
        <TextBlock Text="Address:" />
        <local:AddressView Address="{Binding Path=Person.Address}" />
    </StackPanel>
</Window>
在MainWindow.xaml中:

<local:AddressView DataContext="{Binding Path=Person.Address}" />

然后在AddressView.xaml中

<TextBox Text="{Binding Path=Summary, Mode=OneWay}" IsReadOnly="True" />


这会为我显示摘要。

就像DropBox链接一样!DataContext可能使事情更简单,但这个问题应该是可以解决的。@Tejs:Doing
DataContext=Address和
不显示错误,但也不显示地址摘要。
<local:AddressView DataContext="{Binding Path=Person.Address}" />
<TextBox Text="{Binding Path=Summary, Mode=OneWay}" IsReadOnly="True" />