我想要的是当用户更改文本框 alphaMin_txt
中的值时,属性 AlphaMin
得到更新。
代码隐藏:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private string _alphaMin;
public string AlphaMin
{
get { return _alphaMin; }
set
{
if (value != _alphaMin)
{
_alphaMin = value;
NotifyPropertyChanged();
}
}
}
}
XAML:
<DockPanel DataContext="{Binding MainWindow}">
<TextBox Text="{Binding
Path=AlphaMin,
NotifyOnTargetUpdated=True,
Mode=OneWayToSource,
UpdateSourceTrigger=PropertyChanged}" />
</DockPanel>
这应该重复一百遍,但我已经完成了所有内容,而且对于这种单向更新源代码来说,没有一个是简单明了的。所有 MSN 教程都将一些 UIControl 绑定(bind)到另一个,这是毫无意义的,因为 IntelliSense 向您展示了如何做到这一点。
最佳答案
您的 DockPanel
可能有错误的 DataContext
绑定(bind)。 DataContext 应在窗口级别设置。
<Window ... DataContext="{Binding RelativeSource={RelativeSource Self}}" ..>
当然,这是假设您的 XAML 是 MainWindow.xaml。
如果主窗口的其余部分有不同的 DataContext,那么您可以这样做:
<TextBox Text="{Binding
RelativeSource={RelativeSource AncestorType=Window},
Path=AlphaMin,
NotifyOnTargetUpdated=True,
Mode=OneWayToSource,
UpdateSourceTrigger=PropertyChanged}" />
当然,您应该删除 DockPanel 的 DataContext。
你后面的代码是正确的;无需更改。使用 CallerMemberName
是实现 INotifyPropertyChanged
的好方法。
关于c# - 将文本框绑定(bind)到属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38046032/