本文介绍了WPF简单绑定到INotifyPropertyChanged对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've created the simplest binding. A textbox bound to an object in the code behind.

事件虽然 - 文本框仍然为空。

Event though - the textbox remains empty.

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

The window's DataContext is set, and the binding path is present.

你能说出什么问题?

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");
            }
        }
    }
}


推荐答案

首先删除 DataContext =MainWindow,因为这将设置 DataContext 窗口字符串 MainWindow ,然后指定 ElementName 为您的绑定定义绑定源作为另一个控件与 x:Name =TheBook它不存在于您的窗口。您可以通过从绑定中删除 ElementName = TheBook 并通过分配 DataContext 来实现您的代码,这是默认源如果没有指定,则窗口 TheBook

First of all remove DataContext="MainWindow" as this sets DataContext of a Window to a string MainWindow, then you specify ElementName for your binding which defines binding source as another control with x:Name="TheBook" which does not exist in your Window. You can make your code work by removing ElementName=TheBook from your binding and either by assigning DataContext, which is default source if none is specified, of a Window to TheBook

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

或指定 RelativeSource 绑定到窗口,它暴露了 TheBook

or by specifying RelativeSource of your binding to the Window which exposes TheBook:

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

但由于您无法绑定到字段,您将需要转换 TheBook into property:

but since you cannot bind to fields you will need to convert TheBook into property:

public partial class SimpleBinding : Window
{
    public Book TheBook { get; set; }
    ...
}

这篇关于WPF简单绑定到INotifyPropertyChanged对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 06:53