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.
Related
I just wrote some nice functions, that allow me to add Emojis in a textbox with Inline.Add([Syste.Windows.Controls.Image]). It basically takes a TextBlock as an argument and appends the text/emojis that I want.
Icons is a Dictionary which maps from string to BitmapImage. (unable to use '<' and '>' here somehow)
private void AddTextToString(TextBlock block, string txt)
{
var textRun = new Run(txt);
textRun.BaselineAlignment = BaselineAlignment.Center;
block.Inlines.Add(textRun);
}
private void AddEmojiToString(TextBlock block, string txt)
{
if (!Icons.ContainsKey(txt))
return;
System.Windows.Controls.Image emo = new System.Windows.Controls.Image();
emo.Height = 15;
emo.Width = 15;
emo.VerticalAlignment = VerticalAlignment.Center;
emo.Source = Icons[txt];
block.Inlines.Add(emo);
}
Now I was wondering if there was an elegant way of saving this kind of text to a variable, so that I could bind the TextBlock Text dynamically to it.
Thank you very much in advance!
TextBlock.Inlines is property of type InlineCollection, you can use this type to keep the contents.
This is my first post so I apologise if I do anything wrong :-)
I know a little bit about coding but I'm new to C#. I've created a form and I want to toggle the form BackgroundImage between two different images when a "Change Background" button is clicked. I found this code that will toggle between image and no image:
this.BackgroundImage = this.BackgroundImage == null ? Properties.Resources.image1 : null;
I thought I might be able to use it to achieve what I want but I couldn't get it to work. I'm guessing I need completely different code? I thought an "if" statement would be the way to go but I can't figure that out either.
Thanks in advance for any help.
Imagine you want to switch between 2 images. Use a flag to determine which one is up and then change the image based on that flag.
private int imgId=0;
Then button_click should contains:
this.BackgroundImage = imgId==0 ? Properties.Resources.image2 : Properties.Resources.image1;
imgId=imgId==0 ?1:0;
this.BackgroundImage = this.BackgroundImage == null ? Properties.Resources.image1 : null;
checks if the background is null, then if it is null returns an image and otherwise returns null.
You can use this code for your problem but I advise you to create a variable to check instead of the two images. The equality operator on full images isn't that performant ;)
I'll try to code really clear here and leave the difficult if operator out for better understanding.
//This variable doesn't erase if it's outside the function
private bool firstImage = true;
public function SwitchImage(){
if (firstImage == true){
//set background
this.BackgroundImage = Properties.Resources.image2
//update var
firstImage = false;
} else {
//set background
this.BackgroundImage = Properties.Resources.image1
//update var
firstImage = true;
}
}
I am trying add a background image using the image property in button. The issue I'm facing is that i can't set StreamImageSource as button background. I encountered the error given below if I try to do so.
The Code I use to set Image:
ImageSource iconsource =ImageSource.FromStream(() => new MemoryStream(ImgASBytes));
Button Icon = new Button ();
Icon.Image = iconsource ;
The Error I encounter:
Error CS0266: Cannot implicitly convert type 'Xamarin.Forms.ImageSource' to 'Xamarin.Forms.FileImageSource'. An explicit conversion exists (are you missing a cast?)
ImageSource.FromStream () returns a StreamImageSource (see docs). Button.Image accepts only FileImageSource (see docs).
It means that what you're trying to achieve won't work, no matter how hard you try to cast one into the other.
Button.Image will accept images stored as resources in your platform projects, and loaded either with:
Icon.Image = ImageSource.FromFile ("foobar.png");
or
Icon.Image = "foobar.png";
The accepted answer is true that you can't cast StreamImageSource to FileImageSource, I think that the real question is about how to share images in a PCL and use them on a button, just like one would when creating an Image forms control.
The answer is to have a Grid which contains both a Button and an Image object, where the Image overlaps the Button.
For example, the C# code might look like this:
ImageSource imageSource = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
Button iconButton = new Button ();
iconButton.VerticalOptions = LayoutOptions.FillAndExpand;
iconButton.HorizontalOptions = LayoutOptions.FillAndExpand;
var image = new Image();
image.Source = imageSource;
// So it doesn't eat up clicks that should go to the button:
image.InputTransparent = true;
// Give it a margin so it doesn't extend to the edge of the grid
image.Margin = new Thickness(10);
var grid = new Grid();
// If we don't set a width request, it may stretch horizontally in a stack
grid.WidthRequest = 48;
// Add the button first, so it is under the image...
grid.Children.Add(iconButton);
// ...then add the image
grid.Children.Add(image);
You may have to play with the sizes and thickness values but this should get you a clickable button with an icon.
As of Xamarin.Forms 3.4.0 you can now use ImageButton. You can use embedded images by using an extension method explained in this MS document
Careful with upper- and lowercase in filenames.
I was wondering, why my button-images were shown properly on the simulator, but not on my iPhone.
On the device the filename must match exactly, the simulator doesn't care about upper- and lowercase in filenames.
I use this and it works
var imageA = new Image();
imageA.Source=(FileImageSource)ImageSource.FromFile(allergeneLocation)};
or
var imageA = new Image()
{
BackgroundColor = Color.Teal,
Source = (FileImageSource)ImageSource.FromFile(allergeneLocation)},
};
Here is what I tried:
Button refreshBut = new Button
{
Image = (FileImageSource)
(ImageSource.FromFile("refreshBut.png"))
};
While it compiles I then get an unhandled null reference exception with the description: Object reference not set to an instance of an object. I am not sure if this will help anyone else try to solve this but I am at the same wall.
I'm fairly new to C# (and programming in general) so stick with me if I make any huge errors or talk complete bull.
So what I'm trying to do is have a private void that resizes the background image of a button. I send the name of the button to the private void via a string. Anyway, the code looks something like this:
ButtonResize("Zwaard");
protected void ButtonResize(string Button)
{
string ButNaam = "btn" + Button;
Button Butnaam = new Button();
Butnaam.Text = ButNaam;
if (Butnaam.BackgroundImage == null)
{
return;
}
else
{
var bm = new Bitmap(Butnaam.BackgroundImage, new Size(Butnaam.Width, Butnaam.Height));
Butnaam.BackgroundImage = bm;
}
}
But it doesn't work like that. I can't seem to find a way to declare a new object named the value I have in a string. What I want my code to do is instead of making a button called "Butnaam", I want it to create a button called btnZwaard (the value of the string Butnaam).
How do I tell C# I want the value of the variable to be the name of a new button, not literally what I type?
Thanks in advance.
Are you looking for something like this? By passing the Button to the method you can then act on the object. If this is what you are looking for then you should read Passing Reference-Type Parameters
protected void ButtonResize(Button button)
{
if (button != null && button.BackgroundImage != null)
{
button.BackgroundImage = new Bitmap(button.BackgroundImage, new Size(newWidth, newHeight));
}
}
A string is a piece of text. You subsequently refer to it as a class, which is wrong. Assuming it were right you create a new button rather than "resize its image".
What you want to do to get you started is create a new function in the same class as the dialog that has the button. That function can resize the image of the control.
Edit: this doesn't seem like a good starting point for learning a language, btw. Please find a good online tutorial for starting in C# (e.g. a hello world application).
I am trying to load a BitmapImage at runtime from a URI. I use a default image in my XAML user control which I'd like to replace via databindings. This works.
The problem I'm having is in situations where an invalid file is used for the replacement image (maybe it's a bad URI, or maybe the URI specifies a non-image file). When this happens, I want to be able to check the BitmapImage object to see if it was correctly loaded. If not, I want to stick to the default image being used.
Here's the XAML:
<UserControl x:Class="MyUserControl">
<Grid>
<Image
x:Name="myIcon"
Source="Images/default.png" />
</Grid>
</UserControl>
And the relevant codebehind:
public static readonly DependencyProperty IconPathProperty =
DependencyProperty.Register(
"IconPath",
typeof(string),
typeof(MyUserControl),
new PropertyMetadata(null, new PropertyChangedCallback(OnIconPathChanged)));
public string IconPath
{
get { return (string)GetValue(IconPathProperty); }
set { SetValue(IconPathProperty, value); }
}
private static void OnIconPathChanged(
object sender,
DependencyPropertyChangedEventArgs e)
{
if (sender != null)
{
// Pass call through to the user control.
MyUserControl control = sender as MyUserControl;
if (control != null)
{
control.UpdateIcon();
}
}
}
public void UpdateIcon()
{
BitmapImage replacementImage = new BitmapImage();
replacementImage.BeginInit();
replacementImage.CacheOption = BitmapCacheOption.OnLoad;
// Setting the URI does not throw an exception if the URI is
// invalid or if the file at the target URI is not an image.
// The BitmapImage class does not seem to provide a mechanism
// for determining if it contains valid data.
replacementImage.UriSource = new Uri(IconPath, UriKind.RelativeOrAbsolute);
replacementImage.EndInit();
// I tried this null check, but it doesn't really work. The replacementImage
// object can have a non-null UriSource and still contain no actual image.
if (replacementImage.UriSource != null)
{
myIcon.Source = replacementImage;
}
}
And here's how I might create an instance of this user control in another XAML file:
<!--
My problem: What if example.png exists but is not a valid image file (or fails to load)?
-->
<MyUserControl IconPath="C:\\example.png" />
Or maybe someone can suggest a different/better way to go about loading an image at runtime. Thanks.
Well, BitmapImage class has two events, which will be raised when either download or decoding has failed.
yourBitmapImage.DownloadFailed += delegate { /* fall to your def image */ }
yourBitmapImage.DecodeFailed += delegate { /* fall to your def img */ }
On a side note, if you're trying to implement fallback placeholder: http://www.markermetro.com/2011/06/technical/mvvm-placeholder-images-for-failed-image-load-on-windows-phone-7-with-caliburn-micro/ seems nice.
It's crude, but I found that a non-valid BitmapImage will have width and height of 0.
BitmapImage image;
if(image.Width > 0 && image.Height > 0)
{
//valid image
}
You can try this check
if (bitmapImage.UriSource==null || bitmapImage.UriSource.ToString()).Equals(""))
{
Console.WriteLine("path null");
}
else
{
bitmapImage.EndInit();
}
This has already been answered. Please have a look at this and this. I think that both of them somewhat answer your question but I would prefer the former approach as it even checks for the contentType of the remote resource.
You can also have a look at this post.
Update:
In case of local files, this can be checked by simply creating an Image object using the Uri, or the path. If it is successful, it means the image is a valid image:
try
{
Image image = Image.FromFile(uri);
image.Dispose();
}
catch (Exception ex)
{
//Incorrect uri or filetype.
}