WPF 控件绑定到单个变量

我似乎无法将控件的值绑定到对象。我想将 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


蝴蝶不菲
浏览 388回答 3
3回答

冉冉说

将 str 更改为 auto 属性:公共字符串 str { 获取;放; }将数据上下文更改为:数据上下文 = 这个;DataContext 是将保存您的绑定属性/命令/事件的类。属性/命令/事件需要公开才能被您的视图访问。要使双向绑定工作,您必须通知 UI 绑定属性已更改,为此您需要为包含已在 UI 中绑定的属性的类实现 INotifyPropertyChanged 接口。您将需要私人财产,并且您无法从自动财产中通知。简单示例:public class Sample : INotifyPropertyChanged{&nbsp; &nbsp; private string _str;&nbsp; &nbsp; public string Str&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get { return _str; }&nbsp; &nbsp; &nbsp; &nbsp; set&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _str = value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; NotifyPropertyChanged(nameof(Str));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public event PropertyChangedEventHandler PropertyChanged;&nbsp; &nbsp; public void NotifyPropertyChanged(string propName)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));&nbsp; &nbsp; }}

RISEBY

也许您可以使用 MVVM 灯进行绑定。
打开App,查看更多内容
随时随地看视频慕课网APP