I am making a simple metro app to display an image and some content relevant to the image.
Ex :
image : data
img1 : "Image of a butterfly"
img2 : "Hello sky"
img3 : "Picture of a Golden Retriever"
I have loaded images into a flipview.And relevent data into an array.
<FlipView HorizontalAlignment="Left" Margin="102,147,0,0" VerticalAlignment="Top" Width="627" Height="429" Name="fiImage" SelectionChanged="fiImage_SelectionChanged">
<Image Source="Assets/image1.png" Name="Img1" />
<Image Source="Assets/image2.png" Name="Img2" />
</FlipView>
I have a TextBlock in the xaml named as "tbN". What I want to do is when I change the image using pointer, relevant data should display in the textblock.
I tried following code at selection change event
private void fiImage_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int i = ((FlipView)sender).SelectedIndex;
tbN.Text = a[i]; //error line
}
But when I execute the program, I get an error saying "NullReferenceException was unhandled by the user code: Object reference not set to an instance of an object."
What am I missing?
It seems a[i] has not being initialized and doesn't have values. Is it a global variable?.
Debug your code and check it's content. It must be null.
If it is not null, maybe that array doesn't have the i value. Or maybe it's exceding the array length.
tbN.Text = a[i]; //a[i] must be null, where is it initialized?
SelectionChanged event fires at initialization as well (first child "selected").
Your control (tbN) does not exist at the time.
Check if tbN is null to avoid NRef. Exception!
private void fiImage_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (tbN != null)
{
int i = ((FlipView)sender).SelectedIndex;
tbN.Text = a[i];
}
}
I've found the solution HERE
private void FlipView_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
FlipView fv = sender as FlipView;
if (fv.SelectedItem == null) return;
var item = fv.ItemContainerGenerator.ContainerFromItem(fv.SelectedItem);
if (item == null)
{
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var itemSecondTime = fv.ItemContainerGenerator.ContainerFromItem(fv.SelectedItem);
if (itemSecondTime == null)
{
throw new InvalidOperationException("no item. Why????");
}
});
}
}
Related
I am working on Xamarin forms, where I have used TapGestureRecognizer inside image now on tap of that image I need to get the source of the image in c#. How do I get that?. Why I am doing this is, radio buttons are not available in Xamarin forms, On tap of the image I will check the source of the image if the source is checked image then I need to change the source to unchecked and vice versa.
Here is my XAML code
<Image Scale="0.7" HorizontalOptions="Start" x:Name="radioButton" Source="unchecked.png">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="radioButton_Clicked">
</TapGestureRecognizer>
</Image.GestureRecognizers>
</Image>
Here is my C# code
private void radioButton_Clicked(object sender, EventArgs e)
{
var imageSource = "";//get image source here
if (imageSource == "Checked.png")
{
radioButton.Source = "Unchecked.png";
}
else
{
radioButton.Source = "Checked.png";
}
}
you can achieve like this on radioButton_Clicked action
private void radioButton_Clicked(object sender, EventArgs e)
{
var imageSource = (Image)sender;//get image source here
var selectedImage = imageSource.Source as FileImageSource;
if (selectedImage.File == "Checked.png")
{
radioButton.Source = "Unchecked.png";
}
else
{
radioButton.Source = "Checked.png";
}
}
or you can use the custom plugin for support checked box refer this
https://github.com/XLabs/Xamarin-Forms-Labs
you can cast sender to image control
var imageSender = (Image)sender;
gestures
I'm struggling with changing an image programmatically.
In xaml I have an image like:
<ffimageloading:CachedImage x:Name="n3" Source="N3.png" ></ffimageloading:CachedImage>
In Code I have a TapGesture Recognizer:
var tapn3 = new TapGestureRecognizer();
tapn3.Tapped += tapn3_Tapped;
n3.GestureRecognizers.Add(tapn3);
And the corresponding event:
async private void tapn3_Tapped(object sender, EventArgs e)
{
string level = GetLevel();
if (level == "N3") {
// n3.Source = new Image (Source "n3.png");
} else {
// n3.Source = new Image (Source "n4.png");
}
}
GetLevel, returns a string which is stored in a SQLite DB, and that is working fine.
Off course, the commented lines is the functionality I'm not able to resolve.
If the images are already in your app, you should be able to do this: n3.Source = ImageSource.FromFile("n3.png");
I am working with datepicker control in silverlight. I want to delete input if date is invalid.
I have tried following code :
XAML:
<sdk:DatePicker Height="23" x:Name="datePicker1" Width="179"
DateValidationError="datePicker1_DateValidationError" />
C#:
private void datePicker1_DateValidationError(object sender, DatePickerDateValidationErrorEventArgs e)
{
try
{
if (datePicker1.SelectedDate != null && (Regex.IsMatch(datePicker1.SelectedDate.ToString(), #"^([1-9]|0[1-9]|1[0-2])[- / .]([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])[- / .](1[9][0-9][0-9]|2[0][0-9][0-9])$")))
{
//WORKING FINE
}
else
{
MessageBox.Show("Please enter a valid date");
DatePicker myElement = ((FrameworkElement)System.Windows.Application.Current.RootVisual).FindName("datePicker1") as DatePicker; // search for control named "datePicker1"
myElement.Text = String.Empty;
}
}
catch
{
}
}
But myElement returns null and I can not delete invalid input.
Here's some code I used to do a similar thing:
Code behind:
private void DatePicker_DateValidationError(object sender, DatePickerDateValidationErrorEventArgs e)
{
var MyDatePicker = sender as DatePicker;
DatePickerTextBox dateBox = MyDatePicker.GetVisualDescendants().OfType<DatePickerTextBox>().FirstOrDefault();
if (dateBox != null)
{
dateBox.Text = String.Empty;
}
// clear the SelectedDate property too, otherwise you'll be left with the last valid one
MyDatePicker.SelectedDate = null;
}
Xaml:
<sdk:DatePicker DateValidationError="DatePicker_DateValidationError"/>
I have a number of pickers all on the same form, and all sharing this DateValidationError handler, hence not finding the picker by name.
No need to search for datePicker1 if you have set x:Name already on it. You can access directly it in code behind:
datePicker1.Text = String.Empty;
Moreover, if it's part of some template which is restricting you from accessing it, it is already passed in you method as sender object. You can get it like this:
DatePicker myElement = (DatePicker)sender;
myElement.Text = String.Empty;
I have a 15 borders with an image inside of it in my application that calls a method on MouseUp.. all images have different names.. hence why i want them all to call this one method
<GroupBox Width="75" Height="75">
<Border MouseLeftButtonUp="Image_MouseUp1" Background="Transparent">
<Image x:Name="RedPick5_Image" Height="Auto" Width="Auto"/>
</Border>
</GroupBox>
I want all of them to be able to set the image source of the child (the image is the child of the border if i understand correctly.. how can i do this?
private void Image_MouseUp1(object sender, MouseButtonEventArgs e)
{
//want to set any image that calls this
//something like Sender.Child.Source = ...
}
you need to cast the sender and check
private void Image_MouseUp1(object sender, MouseButtonEventArgs e)
{
var border = sender as Border; // Cast to Border
if (border != null) // Check if the cast was right
{
var img = border.Child as Image; // Cast to Image
if (img != null) // Check if the cast was right
{
// your code
}
// else your Child isn't an Image her you could hast it to an other type
}
// else your Sender isn't an Border
}
you could also do this
private void Image_MouseUp1(object sender, MouseButtonEventArgs e)
{
var border = sender as Border;
if (border == null) // if the cast to Border failed
return;
var img = border.Child as Image;
if (img == null) // if the cast to Image failed
return;
// your code
}
You can do this way in case image is only and immediate child of border:
Image image = (Image)((Border)sender).Child;
image.Source = // Set image source here.
Alternatively you can use FindName
(Image)(sender as Border).FindName("RedPick5_Image");
It will search Border's children recursively for an element named "RedPick5_Image". This may return null if no elements with the specified name is found.
I am trying to add images that I get from my webcam to gridview however each time I get exception. I have separate page to make a picture from webcam and later, I pass image full path to other page. Here are the code snippets:
C#
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//If navigated from PhotoCapturePage
if (m_ToBeNavigatedPageType == typeof(PhotoCapturePage))
{
if (e.Parameter == null)
{
return;
}
Image img = new Image();
img.Width = 64;
img.Height = 64;
img.Source = new BitmapImage(new Uri(e.Parameter.ToString()));
IncidentPictures.Add(img);
IncidentPictureGrid.Items.Add(img);
}
}
XAML:
<GridView ItemsSource="{Binding IncidentPictures}" Name="IncidentPictureGrid" Width="350"></GridView>
Each time IncidentPictureGrid.Items.Add(img) is performed, I receive Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED)) exception.
Does anyone has suggestions?
Thanks in advance,
Miroslawas
Why do you add the image to the Grid.Items collection when you add it to IncidentPictures collection too?
You already bind the GridView's ItemsSource to the collection. Maybe this cause the error ... Remove the IncidentPictureGrid.Items.Add and make sure, that IncidentPictures is an ObservableCollection.