c# - 将文本框绑定(bind)到属性

标签 c# wpf binding textbox

我想要的是当用户更改文本框 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/

相关文章:

c# - C# 中的大型 xml 到 csv

c# - 收集的真实枚举器是如何实现的?

wpf - 如何动态禁用按钮

wpf - 过多的数据绑定(bind)是否会使 WPF 应用程序变慢?有哪些可用的优化技术?

wpf - 将 wpf listview 绑定(bind)到数据集......可能......?

c# - 如何在 Visual C# 中像 C 语言中的#define 一样定义常量?

javascript - 从IE浏览器调用winform函数

c# - PointerMoved 事件未触发

.net - Silverlight 提供什么?

c# - Xamarin.Forms 如何将多个页面的 BindingContext 设置为同一个 ViewModel?