I'm new to WPF and trying a simple example of databinding, but it's not working. My window has a TextBlock, which I bound to a property of the window object. I declared the property in code.
When running this, I see the correct value appearing in the TextBlock. There's also a button, which when clicked updates the property, except I don't see this affecting the TextBlock.
I implemented the INotifyPropertyChanged correctly, as far as I'm able to determine. I also see, when debugging, that something has subscribed to the PropertyChanged event, except it doesn't seem to do anything.
I have 2 questions:
1) Why isn't this working as expected?
2) Is there any easy way to debug during run-time what's causing this, without resorting to third-party tools? From my cursory knowledge, it seems to me the debugging support in WPF is sorely lacking.
The XAML is (not including the "standard" XAML window element):
<TextBlock Height="28" Name="label1" VerticalAlignment="Top"
Text="{Binding Path=TheName}"
Grid.Row="0"
></TextBlock>
<Button Height="23" Name="button1" VerticalAlignment="Stretch" Grid.Row="1"
Click="button1_Click">
Button
</Button>
The code in the window class is:
public partial class Window1 : Window
{
protected MyDataSource TheSource { get; set; }
public Window1()
{
InitializeComponent();
TheSource = new MyDataSource();
TheSource.TheName = "Original"; // This works
this.label1.DataContext = this.TheSource;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
TheSource.TheName = "Changed"; // This doesn't work
}
}
public class MyDataSource : INotifyPropertyChanged
{
string thename;
public string TheName
{
get { return thename; }
set { thename = value; OnPropertyChanged(thename); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}