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

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

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}"/>

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; }
    ...
}
于 2013-07-31T10:55:48.023 に答える