Smallestearth Smallestearth - 6 days ago 4
C# Question

Data binding no error but could not the see the binded output

I am trying to learn WPF and I am stuck with the very initial binding example. I want to see the text in the textbox from the property present in the code. I have seen some relevant questions and I have tried their answers but unfortunately none of them fits my need. Moreover if someone could tell me some nice tutorials that starts from basic and proceed to advanced level. I am looking in msdn tutorials but I find them very complex (or too much text) making things more complicated.

MainWindow.xaml.cs

namespace WpfApplication1
{
public partial class MainWindow : Window
{
public string Name { get; set; }

public MainWindow()
{
Name = "Dummy";
InitializeComponent();
DataContext = this;


}
}
}


MainWindow.xaml

<Window x:Class="WpfApplication1.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:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Text="{Binding Path=Name}"></TextBox>
</Grid>
</Window>

Answer

The property Name hides the Name property of the base class (and Visual Studio warns you about this). You're setting the new property, while the Binding in XAML uses the base class property.

Choose a different property name:

public string MyName { get; set; }

public MainWindow()
{
    MyName = "Dummy";
    InitializeComponent();
    DataContext = this;
}

XAML:

<TextBox Text="{Binding Path=MyName}" />