Hỏi đáp

Chia sẻ kiến thức, cùng nhau phát triển

Binding Textbox trong WPF

20:21 27-09-2021 773 lượt xem 2 bình luận

Em chỉ mới học lập trình và em đang tìm hiểu về WPF, em muốn hỏi mọi người cách để mình set Text của một Textbox bằng giá trị của một string tên là name với giá trị bất kì, và khi em thay đổi Text của Textbox thì giá trị của string name đó cũng thay đổi theo ạ. Em xin lỗi nếu như câu hỏi của em khó hiểu :<<

Em cảm ơn mọi người ạ !

Bình luận

Để bình luận, bạn cần đăng nhập bằng tài khoản Howkteam.

Đăng nhập
Supporter Moderator đã bình luận 20:39 27-09-2021

Bạn tham khảo Code bên dưới thử nha:
Code XAML

<Window x:Class="EventAppWPF.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:EventAppWPF"
        mc:Ignorable="d"
        Title="MainWindow" Height="200" Width="470">
    <Grid>
        <TextBox Text="{Binding MyName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
    </Grid>
</Window>

Code CS

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;

namespace EventAppWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private String _myName;
        public String MyName
        {
            get { return _myName; }
            set { _myName = value; OnPropertyChanged(); }
        }


        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string nameProp = null) => PropertyChanged(this, new PropertyChangedEventArgs(nameProp));
    }
}

 

Câu hỏi mới nhất