C# WPF Hello World 4


This entry is part 4 of 4 in the series WPF Hello World

In this post we are continuing over from the last post. Here we are going to display some text on a label on the main window. The source of the text is from a class we have. The class reads the text file that the user selected and displays the number of characters in the file.

The class that we have added in the previous post is called ProcessFile.cs. It has a method called CharsInFile().

x:Name

How does the class we wrote communicate with the label on on main window? The label must have a name. We need to give it a name with x:Name. Below is our XAML code in MainWindow.xaml.

        <Label x:Name="lblCharsNumber" Content="Label" HorizontalAlignment="Left" Margin="101,265,0,0" 
               VerticalAlignment="Top" Width="234"/>

In our class we have the following code that sends the string back to the label. When we created the class it was automatically put in the correct namespace: WpfApp3.

     MainWindow win = (MainWindow)Application.Current.MainWindow;
     win.lblCharsNumber.Content = CharCount.ToString() + " characters in file.";

In the above code we have previously declared an integer and given it a value. The integer is CharCount.

When we run the program, select a text file by Browsing out to it, we get the following. The red text is what I added in Photoshop.

Series Navigation<< C# WPF Hello World 3