D
D
Danil Vaskevich2021-12-11 21:07:31
WPF
Danil Vaskevich, 2021-12-11 21:07:31

How to bind a TextBox to a variable in C# using MVVM pattern?

I have a task for the MVVM pattern, but there was a problem when implementing the pattern itself. I don't know how to bind a field in a TextBox to a variable inside the code. I tried using DataContext but didn't fully understand how it works.
Code attached:
C#

public partial class MainWindow : Window
    {
        private string dir;

        public string Dir
        {
            get => dir;
            set
            {
                dir = value;
            }
        }
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();

            string[] dirs = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));

            foreach (var i in dirs)
            {
                lbFiles.Items.Add(i);
            }
        }
    }

XAML
<Window x:Class="home_wpf_mvvm_files.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:home_wpf_mvvm_files"
        mc:Ignorable="d"
        DataContext="{Binding MainWindow, Source={StaticResource Dir}}"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="3*"></RowDefinition>
            <RowDefinition Height="3*"></RowDefinition>
            <RowDefinition Height="30*"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"></ColumnDefinition>
            <ColumnDefinition Width="10*"></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <Button Margin="5,5" FontSize="15" FontWeight="Bold">Open</Button>
        <TextBox Name="tbDirectory" Grid.Column="1" Margin="5,5"></TextBox>
        <Label Grid.Row="1" Grid.ColumnSpan="2" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Top" FontWeight="Bold">Files</Label>
        <ListBox Name="lbFiles"  Grid.Row="2" Grid.ColumnSpan="2" Margin="10"></ListBox>
    </Grid>
</Window>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JeremiSharkboy, 2021-12-21
@JeremiSharkboy

Here is a good example https://streletzcoder.ru/realizatsiya-patterna-mvv...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question