为了账号安全,请及时绑定邮箱和手机立即绑定

WPF 控件绑定到单个变量

WPF 控件绑定到单个变量

C#
蝴蝶不菲 2021-08-07 15:46:17
我似乎无法将控件的值绑定到对象。我想将 a 绑定TextBox到一个string对象,想法是当文本框的文本更改时,它也应该自动更改对象。无法弄清楚我做错了什么。这是我尝试过的:主窗口.xaml.cs:public partial class MainWindow : Window    {        string str;    public MainWindow()    {        InitializeComponent();        this.DataContext = str;    }    private void Button_Click(object sender, RoutedEventArgs e)    {    }}和 MainWindow.xaml:<Window x:Class="WpfApp1.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"        xmlns:local="clr-namespace:WpfApp1"        mc:Ignorable="d"        Title="MainWindow" Height="150" Width="150">    <Grid Margin="0,0,642,319">        <TextBox HorizontalAlignment="Left" Height="23"  TextWrapping="Wrap" Text="{Binding str}" VerticalAlignment="Top" Width="120" Margin="0,0,-120,-46" />        <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="Button_Click" Height="23" Margin="0,28,-75,-51" RenderTransformOrigin="0.423,2.257" />    </Grid></Window>所以,当我在文本框中输入一些东西并点击按钮时,我应该在str调试时看到文本,但它总是null
查看完整描述

3 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

将 str 更改为 auto 属性:


公共字符串 str { 获取;放; }


将数据上下文更改为:


数据上下文 = 这个;


DataContext 是将保存您的绑定属性/命令/事件的类。属性/命令/事件需要公开才能被您的视图访问。


要使双向绑定工作,您必须通知 UI 绑定属性已更改,为此您需要为包含已在 UI 中绑定的属性的类实现 INotifyPropertyChanged 接口。您将需要私人财产,并且您无法从自动财产中通知。


简单示例:


public class Sample : INotifyPropertyChanged

{

    private string _str;

    public string Str

    {

        get { return _str; }

        set

        {

            _str = value;

            NotifyPropertyChanged(nameof(Str));

        }

    }


    public event PropertyChangedEventHandler PropertyChanged;


    public void NotifyPropertyChanged(string propName)

    {

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));

    }

}


查看完整回答
反对 回复 2021-08-07
?
RISEBY

TA贡献1856条经验 获得超5个赞

也许您可以使用 MVVM 灯进行绑定。


查看完整回答
反对 回复 2021-08-07
  • 3 回答
  • 0 关注
  • 387 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信