0

我是 WPF 的新手,过去几天我一直在为此烦恼。我正在尝试将文本框的基本绑定设置为字符串属性。我遵循了 MS 教程,但似乎没有任何效果。

这是电子邮件类,我正在尝试绑定其主题属性以显示在文本框中

public class Email : INotifyPropertyChanged
{
    private string _subject;

    public string Subject
    {
        get { return _subject; }
        set
        {
            _subject = value;
            OnPropertyChanged("Subject");
        }
    }

    private string _contents;

    public string Contents
    {
        get { return _contents; }
        set
        {
            _contents = value;
            OnPropertyChanged("Contents");
        }
    }

    private Category _category;

    public Category Category
    {
        get { return _category; }
        set
        {
            _category = value;
            OnPropertyChanged("Category");
        }
    }

    public Email()
    {
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string info)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(info));
        }
    }
}

这是 UserControl 内的电子邮件设置器,它是文本框的父级:

private Email _email;

public Email Email
{
    get { return _email; }
    set
    {
        _email = value;
        if (_email != null)
        {
            Binding myBinding = new Binding("Subject");
            myBinding.Source = _email;
            tbSubject.SetBinding(TextBlock.TextProperty, myBinding);
        }
    }
}

tbSubject 永远不会设置为任何内容,即使传递的电子邮件不为空并且有主题,它也始终为空!如果我这样做:

public Email Email
{
    get { return _email; }
    set
    {
        _email = value;
        if (_email != null)
        {
            tbSubject.Text = _email.Subject;
        }
    }
}

它工作正常。我不明白我做错了什么。

4

1 回答 1

0

我想我明白了。这是我必须做出的改变:

    public partial class EmailContentsTemplate : UserControl, INotifyPropertyChanged
{
    private Email _email;

    public Email Email
    {
        get { return _email; }
        set
        {
            _email = value;
            OnPropertyChanged("Email");
        }
    }


    public EmailContentsTemplate()
    {
        InitializeComponent();

        DataContext = this;

        Binding myBinding = new Binding("Email.Subject");
        myBinding.Source = this;
        tbSubject.SetBinding(TextBlock.TextProperty, myBinding);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string info)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(info));
        }
    }
}

所以我将源更改为“this”并让用户控件实现 INotifyPropertyChanged。现在它起作用了。

或者我通过 XAML 让它工作

<TextBox x:Name="tbSubject" Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding Email.Subject}"/>
于 2013-09-15T20:20:43.587 回答