I’d like to be able to see the counter value in the textblock which incremented on a click of the button. I need to bind it to the textblock. I am wondering what will be the correct way to do it.
XAML:
<TextBlock Text="{Binding Path=counter}" />
<Button x:Name="Nextbt" Content="Next" Click="ClickNextButton"/>
C#:
private void ClickNextButton(object sender, System.Windows.RoutedEventArgs e){
counter += 1;
if (counter == 1)
{
}
if (counter == 2)
{
}}
Thank you in advance.
1) Make a public property, that returns the counter value. Name it “Counter”
2) Implement INotifyPropertyChanged and call PropertyChanged(new PropertyChangedEventArgs(“Counter”)) for every change of the counter-value
3) Change your markup as follows:
This is only one possiblity of many. This link leads you to an overview of DataBinding. I could imagine that this document will clarify the above steps.
Update
As you wished in your comment, here an example, I assume you are in the main-window. I have changed some things against the above sequence: I have set the DataContext in the constructor. Therefore it is no more necessary to use a relative source for the Binding. Both ways are possible (and both are not very elegant, but to learn WPF-Databinding, they are appropriate). Maybe you try both, the only difference is the binding-declaration and the constructor code.
And the XAML: