C#/WPF (MVVM)

[C# WPF / MVVM] 데이터 바인딩 (Data Binding)

F급 개발자 2023. 7. 24. 20:34
728x90
반응형

해당 포스트는 C# WPF .NET 6 기반, NuGet "CommunityToolkit.Mvvm"으로 작성되었습니다.

 

 

https://mydevenotes.tistory.com/7

 

[Visual Studio] NuGet 다운로드

- Visual Studio NuGet 다운로드 방법을 알아보겠습니다. 1. Visual Studio 2022 (버전은 상관없습니다.) 실행시킵니다. 2. 프로젝트 우클릭 - NuGet 패키지 관리 클릭합니다. 3. 원하는 NuGet을 찾아보기에서 검

mydevenotes.tistory.com

NuGet "CommunityToolkit.Mvvm"을 설치합니다.

 

 

MainWindow.xaml

<Window x:Class="DataBinding.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:DataBinding"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>       
      
        <TextBox Grid.Row="0" Text="{Binding Tb_Text}"/>   
        <Button Grid.Row="1" Content="버튼" Command="{Binding Btn_ButtonCommand}"/>
    </Grid>
</Window>

 

MainWindow.cs

using System.Windows;

namespace DataBinding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = Main_Model.main_ViewModel;
        }
    }
}

 

Main_Model.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataBinding
{
    public class Main_Model
    {
        public static Main_ViewModel main_ViewModel = new Main_ViewModel();
    }
}

 

Main_ViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Windows;

namespace DataBinding
{
    public partial class Main_ViewModel : ObservableObject
    {
        public Main_ViewModel()
        {
            Main_Model.main_ViewModel = this;
        }


        [ObservableProperty]
        private string tb_Text = "";

        [RelayCommand]
        private void Btn_Button()
        {
            MessageBox.Show(Tb_Text);
        }
    }
}

 

- 실행 결과

728x90
반응형