C# – WPF – EightBall Application – simple code

In this article I present a code from the book “Pro WPF 4.5. in C#“, which I consider useful and interesting. The application concerns building a simple program where you may ask a yes-no question and get a random answer. It looks like this:



So, what do we have in this application?

  • A XAML code;
  • A code, associated with the button click, within the XAML;
  • A class, where we keep the strings for the prediction and a method for a random answer.

With these three simple building blocks, we achieve a simple application. Let’s examine them. The XAML looks like this:

After declaring the namespaces and the title, we build a grid. Three rows are defined: the first and the last ones are equal (that is seen from lines 7 to 9). The colorful effect is obtained through the GradientStop property of LinearGradientBrush (lines 13 to 19). Then we notice the three elements, put in the three rows – TextBox (defined on row 20), Button (on row 26) and a new TextBox (on row 32). Thus in simply 40 lines we have “painted” with code our XAML interface.

Once, the button is clicked, the code behind the XAML is activated. This is how it looks like:

What do we have there? The required “InitializeComponent()” method. Then simply a method, telling the application how to react upon a clicked button. In order to make it dramatic :), the first two lines of the method initiate a small waiting, thus you get the impression that the application is actually thinking upon your question. Then a new object from the class “AnswerGenerator”, named “generator” is created. Then the property “Text” of the textbox, named “txtAnswer” receives the result from the method “GetRandomAnswer”, implemented over the object “generator”, containing in himself the text from the text question. At the end the cursor is fixed.

The last part of the application building is the building of the class “AnswerGenerator”. In this class we see one array of strings, containing the answers and a method “GetRandomAnswer(string)”. This method is accessed from the code behind in XAML. It returns a random string from the array answers. This is how it looks like:

In this example you have seen the presentation of a simple application. Its target is to show you what can be done with WPF C#. And it is quite a lot!

Enjoy the code (which is not actually mine) & have a good day 🙂


VBA Developer

Tagged with: , , , , , , , ,