WPF - 将文本框文本绑定到 class 属性
WPF - Binding Textbox Text to a class property
我正在对我的 WPF 项目进行一些更改以减少它的弃用率。
我想做的一件事是将我的 Textbox.Text
值绑定到一个简单的 Class,如下所示。
<TextBox x:Name="txtNCM"
Grid.Column="1"
Margin="5"
MaxLength="8"
Text="{Binding Path=Name}"
</TextBox>
public partial class wCad_NCM : UserControl, INotifyPropertyChanged
{
private string name;
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get { return name; }
set
{
name = value;
OnPropertyChanged("Name");
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public wCad_NCM()
{
InitializeComponent();
}
}
每次我使用Immediate Window 显示Name 的值时,它显示为null。我对此很陌生,所以我不得不寻找类似的情况来适应,但我不知道如何让它工作:(
您需要设置 DataContext
并给 Name
一个值。
为此,请更改您的构造函数以包含此内容:
public wCad_NCM()
{
InitializeComponent();
DataContext = this; // Sets the DataContext
Name = "Test";
}
这应该可以正常工作,但通常是不好的做法。有关详细信息,请参阅 http://blog.scottlogic.com/2012/02/06/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight.html。
另外,我尝试 运行 这个和 运行 解决名字隐藏问题。尝试使用 Name
以外的变量名称,因为 FrameworkElement
已经包含它。
我正在对我的 WPF 项目进行一些更改以减少它的弃用率。
我想做的一件事是将我的 Textbox.Text
值绑定到一个简单的 Class,如下所示。
<TextBox x:Name="txtNCM"
Grid.Column="1"
Margin="5"
MaxLength="8"
Text="{Binding Path=Name}"
</TextBox>
public partial class wCad_NCM : UserControl, INotifyPropertyChanged
{
private string name;
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get { return name; }
set
{
name = value;
OnPropertyChanged("Name");
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public wCad_NCM()
{
InitializeComponent();
}
}
每次我使用Immediate Window 显示Name 的值时,它显示为null。我对此很陌生,所以我不得不寻找类似的情况来适应,但我不知道如何让它工作:(
您需要设置 DataContext
并给 Name
一个值。
为此,请更改您的构造函数以包含此内容:
public wCad_NCM()
{
InitializeComponent();
DataContext = this; // Sets the DataContext
Name = "Test";
}
这应该可以正常工作,但通常是不好的做法。有关详细信息,请参阅 http://blog.scottlogic.com/2012/02/06/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight.html。
另外,我尝试 运行 这个和 运行 解决名字隐藏问题。尝试使用 Name
以外的变量名称,因为 FrameworkElement
已经包含它。