0

I wrote the code in C#.

I was writing a simple example of clicking the button to add the values in the two text boxes.

  1. MainWindow.xaml.cs

namespace bhwpftest
{
    public partial class MainWindow : Window
    {
        
        **Calc calc = new Calc();**
        

        public MainWindow()
        {
            InitializeComponent();
            **panel.DataContext = calc;**
        }

1-1. MainWindow.xaml


            <TextBox Grid.Column="0" Text="{Binding **Value1**}"></TextBox>
            <TextBox Grid.Column="1" Text="{Binding **Value2**}"></TextBox>
            <TextBlock Grid.Column="3" Text="{Binding **Result**}" ></TextBlock>

and

  1. MainWindow.xaml.cs
//Calc calc = new Calc(); //dosen't work
**public Calc calc { get; set; } = new Calc();**

...

public MainWindow()
        {
            InitializeComponent();
            //panel.DataContext = calc;
        }

2-1. MainWindow.xaml

<Window x:Class="bhwpftest.MainWindow"
.
.
.
        **DataContext="{Binding RelativeSource={RelativeSource Self}}"**
        >

            <TextBox Grid.Column="0" Text="{Binding **calc.Value1**}"></TextBox>
            <TextBox Grid.Column="1" Text="{Binding **calc.Value2**}"></TextBox>
            <TextBlock Grid.Column="3" Text="{Binding **calc.Result**}" ></TextBlock>
    

</Window>

I think it is same working

I want to know why there is such a difference and what the difference is.

Thank you.

  • Does this answer your question? [What is the difference between a field and a property?](https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property) – David May 30 '23 at 13:33

0 Answers0