我是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永远不会被设置为任何东西,即使传递的电子邮件不是null并且有主题,它也总是空的!如果我这样做:
public Email Email
{
get { return _email; }
set
{
_email = value;
if (_email != null)
{
tbSubject.Text = _email.Subject;
}
}
}
它工作正常。我不明白我做错了什么。
答案 0 :(得分: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));
}
}
}
所以我将源代码改为"这个"并使用户控件实现INotifyPropertyChanged。现在它有效。
或者我通过XAML
开始工作<TextBox x:Name="tbSubject" Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding Email.Subject}"/>