문제

Question:

Trying to essentially say IF my TextBlock contains "X" THEN Perform the IF but I don't know how to write that in the correct context.

Example:

If the word "Chocolate" is in the TextBlock I'd like to show an Image of "Chocolate" (I already know how to correctly display the image, my problem is with the IF Statement itself)

I'm new to this kinda stuff and I'd like like to know for future reference.

Problems:

Right now, I don't know HOW to perform an IF statement on a TextBlock/String in a way that actually works.

Attempted:

 if (string content.contains("Chocolate"));
        {

            Uri Pure = new Uri("Images/ChocolatePortrait.png", UriKind.Relative);
            BitmapImage imageSource = new BitmapImage(Pure);
            image2.Source = imageSource;


        }

if (textBlock.text = ("Chocolate"));
        {

            Uri Pure = new Uri("Images/ChocolatePortrait.png", UriKind.Relative);
            BitmapImage imageSource = new BitmapImage(Pure);
            image2.Source = imageSource;


        }
도움이 되었습니까?

해결책

The problem is that you are terminating the if-statement prematurely by a semicolon ;!

if (textBlock.Text.Contains("Chocolate")) // <= removed the ";"
{
    Uri Pure = new Uri("Images/ElfPortrait.png", UriKind.Relative);
    BitmapImage imageSource = new BitmapImage(Pure);
    image2.Source = imageSource;
}

Also the property is Text with an upper case "T". In C# Text and text are two different identfiers!

Many programmers prefer to write the opening brace on the same line. This makes it clearer that the end of the line is not the end of a statement:

if (condition) {
    statement-sequence
}

Note that "The Chocolate is fine!".Contains("Chocolate") returns true. If the whole string must be equal to the word then compare with textBlock.Text == "Chocolate"

다른 팁

use == to test for equality

if (textBlock.Text == "Chocolate")
        {

            Uri Pure = new Uri("Images/ChocolatePortrait.png", UriKind.Relative);
            BitmapImage imageSource = new BitmapImage(Pure);
            image2.Source = imageSource;


        }

you could also do something like this:

if (textBlock.Text.Contains("Chocolate", StringComparison.OrdinalIgnoreCase))
{
  // ....
}

if you're looking for the word "chocolate" in the text block's text and you don't want the check to be case sensitive.

if(YOUR_STRING_HERE.Contains(STRING_YOU_WANT_TO_FIND))
{
   //do your stuff here
}

You can either check for equality with:

if (textBlock.text.Equals("Chocolate");
{
//do whatever must be done here
}

Or you can also use == (then you dont need to check for null before). However, with the 'Equals' you can also use the overload functions e.g. to ignore the case.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top