我很难让我的WPF正确使用数据绑定。在XAML中,我有以下内容:
....
<TextBox Name="txt_FirstName" Text="{Binding Path=currentApplication.FirstName, UpdateSourceTrigger=PropertyChanged}" />
....
我有以下CS代码:
namespace WPF1
{
public partial class MainWindow : Window
{
personalApp currentApplication = new personalApp ();
public MainWindow()
{
InitializeComponent();
}
}
}
引用以下两个类:
class personalApp : INotifyPropertyChanged
{
private Person person = new Person();
public string FirstName
{
get { return person.FirstName; }
set
{
person.FirstName = value;
this.OnPropertyChanged("FirstName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(
this, new PropertyChangedEventArgs(propName));
}
}
class Person
{
private string firstName = "";
get { return firstName; }
set { FirstName = value; }
}
我在代码中暂停它并逐步检查,但是当我更新应用程序中的txt_FirstName时,它似乎永远不会设置firstName对象。
我哪里错了?
答案 0 :(得分:4)
您需要更新XAML
绑定,并使用DataContext
设置窗口的TextBox
。
namespace WPF1
{
public partial class MainWindow : Window
{
personalApp currentApplication = new personalApp ();
public MainWindow()
{
InitializeComponent();
this.DataContext = currentApplication;
}
}
}
更新XAML:
<TextBox Name="txt_FirstName" Text="{Binding FirstName, UpdateSourceTrigger=PropertyChanged}" />
答案 1 :(得分:1)
我已经更正了代码。
对于文本框:
<TextBox Name="txt_FirstName" Height="30" Background="Beige"
Text="{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged}" />
C#代码
namespace Wpf1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new personalApp();
}
}
internal class personalApp : INotifyPropertyChanged
{
private Person person = new Person();
public string FirstName
{
get { return person.FirstName; }
set
{
person.FirstName = value;
this.OnPropertyChanged("FirstName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(
this, new PropertyChangedEventArgs(propName));
}
}
internal class Person
{
public string FirstName { get; set; }
}
}
答案 2 :(得分:0)
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
或者如果您不想为自己(窗口)分配数据上下文,因为您可能有其他datacontext进入窗口,您可以在xaml中添加: 给你的窗口一个名字:
<Window .... x:Name="this"...
然后
<TextBox Name="txt_FirstName" Text="{Binding ElementName=this,
Path=currentApplication.FirstName/>
答案 3 :(得分:-1)
“更新应用程序中的txt_FirstName”是什么意思?
如果直接设置文本框的值,则应尝试设置currentApplication
的值而不是文本框值