7

我创建了最简单的绑定。绑定到后面代码中的对象的文本框。

事件虽然 - 文本框仍然是空的。

设置了窗口的 DataContext,并且存在绑定路径。

你能说有什么问题吗?

XAML

<Window x:Class="Anecdotes.SimpleBinding"
        x:Name="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="SimpleBinding" Height="300" Width="300" DataContext="MainWindow">
    <Grid>
        <TextBox Text="{Binding Path=BookName, ElementName=TheBook}" />
    </Grid>
</Window>

背后的代码

   public partial class SimpleBinding : Window
    {
        public Book TheBook;

        public SimpleBinding()
        {
            TheBook = new Book() { BookName = "The Mythical Man Month" };
            InitializeComponent();
        }
    }

图书对象

public class Book : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }

    }

    private string bookName;

    public string BookName
    {
        get { return bookName; }
        set
        {
            if (bookName != value)
            {
                bookName = value;
                OnPropertyChanged("BookName");
            }
        }
    }
}
4

1 回答 1

5

首先DataContext="MainWindow"将这组DataContexta删除Windowstring MainWindow,然后ElementName为您的绑定指定将绑定源定义为另一个控件,x:Name="TheBook"该控件在您的Window. ElementName=TheBook您可以通过从绑定中删除以及通过分配DataContext(如果未指定默认源,则为默认源)Window来使您的代码工作TheBook

public SimpleBinding()
{
    ...
    this.DataContext = TheBook;
} 

或通过指定RelativeSource绑定到Windowwhich 暴露TheBook

<TextBox Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=TheBook.BookName}"/>

但由于您无法绑定到字段,因此您需要转换TheBook为属性:

public partial class SimpleBinding : Window
{
    public Book TheBook { get; set; }
    ...
}
于 2013-07-31T10:55:48.023 回答