Image from ImageSource - c#

I tried to follow the following example by #CraigDunn with the sample code
someButton.Image = ImageSource.FromFile("imageName.png");
My own try looks like this:
_NavBarPrevPage = new Button
{
Image = ImageSource.FromResource("media_step_back.png")),
BackgroundColor = Color.Red,
TextColor = Color.White,
};
For me, the IDE tells me:
The type Xamarin.Forms.ImageSource can't be converted to Xamarin.Forms.FileImageSource. An explicit conversion exists. Perhaps a conversion is missing.
I think I'm doing exactely what #CraigDunn proposed.
What am I doing wrong?
I've tried the following, and I was able to get rid of the conversion errors in the current answer, but the image is not shown on the button, while it is shown in an image, so the file name is correct:
var nImg = new FileImageSource()
{
File = "media_step_back.png",
};
_NavBarPrevPage = new Button
{
Image =nImg,
};

If the thing you need is a button with image that is implementing by code-behind :
Button button = new Button
{
BackgroundColor = Color.Red,
Font = Font.Default,
FontSize = 10,
TextColor = Color.White,
HeightRequest = 35,
WidthRequest = 80
};
button.Image = "media_step_back.png";
this.Content = button;
Please remember to put the image file (media_step_back.png) in your target platform's resource folder
UPDATE:
You problem were you didn't add the image source in the Property folder and target platform's resource folder (Please note that in below example, I have added a xamarin.png image in each Xamarin "Property" folder, Android's "Resource" and iOS's "Resource" folder)
Below is the updated code that I placed the button into a StackLayout (which also able to works if without StackLayout) :
public class MainPageNew : ContentPage
{
public MainPageNew()
{
StackLayout parent = new StackLayout();
Button button = new Button
{
BackgroundColor = Color.Red,
Font = Font.Default,
FontSize = 10,
TextColor = Color.White,
HeightRequest = 300,
WidthRequest = 80
};
//button.Image = "media_step_back.png";
button.Image = "xamarin.png";
parent.Children.Add(button);
this.Content = parent;
}
Android
iOS:
This is the download link of the updated code.

Related

c# Expander content is not on the left

I have the problem that the content of the expander does not start at the left, how can I solve this?
As you can see on the picture, the contents of my expander are not shown to the far left. I have tried many settings, unfortunately I do not come to the solution. The expander itself also seems to have an edge opposite the stackpanel, which I also want to avoid.
Above the expander you can see a grid, which contains a text block with content. This grid has the right mass within the higher-level stack panel.
Expander exp = new Expander
{
Header = "TestExpander",
Width = spStackPanel.Width,
ExpandDirection = ExpandDirection.Down,
IsExpanded = true,
BorderBrush = Brushes.Yellow,
BorderThickness = new Thickness(1),
HorizontalAlignment = HorizontalAlignment.Left,
HorizontalContentAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
VerticalContentAlignment = VerticalAlignment.Top,
};
TextBox tx = new TextBox
{
Text = "testText"
};
exp.Content = tx;
spStackPanel.Children.Add(exp);
I can't comment so apologies for the somewhat vague answer, but it might help to share the styling and XAML used to create your screenshot. By default that isn't how an Expander looks, so my guess is that something in your styling or one of the higher level controls (e.g. StackPanel or Grid) is affecting the layout of the Expander.
Example being possibly a keyless style for TextBox that applies padding and/or horizontal alignment, which would then affect the content you're adding by creating a new TextBox in your snippet to give it that odd alignment.
I have written a test here, directly in a .cs file WITHOUT XML:
buttonGrid = new Grid();
buttonGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(50) });
buttonGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(50) });
Expander exp = new Expander()
{
Header = "Test Expander",
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(0),
IsExpanded = true
};
TextBlock label = new TextBlock()
{
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(0),
Text = "Test Text"
};
exp.Content = label;
Grid.SetRow(exp, 0);
buttonGrid.Children.Add(exp);
TextBlock text = new TextBlock()
{
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(0),
Text = "Test Text",
Foreground = Brushes.White
};
Grid.SetRow(text, 1);
buttonGrid.Children.Add(text);
I know that an expander doesn't usually look like this, so I ask my question ;-)
maybe someone has me a tip to look for.

Xamarin.Forms CollectionView View Recycling Issues

So I am using a CollectionView to display a list of entities that, when pressed, toggle between a opened and closed state. I did this by animating the HeightRequest parameter of the parent container of the view that was pressed, then adding whatever views I wanted to show in the view's expanded state. Here is the code snippet for that:
var animate = new Animation(d => this.HeightRequest = d,
this.Bounds.Height, this.Bounds.Height + 300, Easing.CubicOut);
animate.Commit(this, "a", length: 500);
this.layout.Children.Add(this.candidateList);
this.layout.Children.Add(this.openButton);
This works fine, however, if I scroll down the list, I see that there are views that are also expanded even though I did not touch them previously, more so every full page of scrolling later. Some even include the views that I've added to the expanded state, showing incorrect data. I have assumed that this is due to the recycling mechanics of the CollectionView work in order to save on rendering costs, but there must be some way to fix this. Here is the code for relevant views:
var officesList = new CollectionView
{
ItemTemplate = new DataTemplate(typeof(OfficeListView)),
HorizontalOptions = LayoutOptions.FillAndExpand,
ItemsLayout = new LinearItemsLayout(ItemsLayoutOrientation.Vertical)
{
SnapPointsType = SnapPointsType.None,
ItemSpacing = 10,
},
Margin = new Thickness(20, 5),
ItemSizingStrategy = ItemSizingStrategy.MeasureAllItems,
Footer = " ",
FooterTemplate = new DataTemplate(() =>
{
return new StackLayout
{
Margin = new Thickness(20, 10),
Children = {
new LocorumLabels.MediumLabel
{
Text = "x Results | No filters applied" //TODO: Bind these to footer
}
}
};
})
};
The next snippet is the CollectionsView within an expanded "Office":
this.candidateList = new CollectionView
{
ItemTemplate = new DataTemplate(typeof(CandidateDetailView)),
HorizontalOptions = LayoutOptions.FillAndExpand,
ItemsLayout = new LinearItemsLayout(ItemsLayoutOrientation.Vertical)
{
SnapPointsType = SnapPointsType.None,
//ItemSpacing = 10,
},
Margin = new Thickness(10, 5),
ItemSizingStrategy = ItemSizingStrategy.MeasureAllItems,
Footer = " ",
HeightRequest = 300
};
And here is a video showing what is going on:
https://youtu.be/Ltg2o8BwfwY
Hopefully someone can let me know of a solution. Many thanks.
You are right on the cause.
As CollectionView uses DataTemplate you need to set your views and your data in such a way that when recycled the view appears as it should.
The non-obvious part to keep the animation working is to call the animation as of now but when it completes to set the value in data that would alter the view from the state before the animation to the state after the animation.

How do I change UIPickerView text color in renderer view using Xamarin.Forms.iOS?

I have used UIPickerView in ios renderer file.I tried to change text and background color of view. Used SetValueForKeyPath override method to change text color. While picker initially loaded into view text color was not changed but it does when I change selected index(Problem with initial loading).
protected override void OnElementChanged(ElementChangedEventArgs<CustomGrid> e)
{
if (e.NewElement != null)
{
var nativeView = new UIPickerView();
nativeView.Model = new PickerSource();
nativeView.BackgroundColor = UIColor.Yellow;
nativeView.SetValueForKeyPath(UIColor.Red, (NSString)"textColor");
CGRect cGRect = new CGRect(0, 0, 100, 100);
SetNativeControl(nativeView);
}
base.OnElementChanged(e);
}
I advise against using a PickerRenderer to change the text color, because the Xamarin.Forms.Platform.iOS.PickerRenderer is very complex; it's actually a UIToolbar, UIBarButtonItem and a UITextField combined into a UIPickerView.
The code for Xamarin.Forms.Platform.iOS.PickerRenderer is open-source if you'd like to see how the Xamarin.Forms team initialized a Picker on iOS.
Xamarin.Forms.Picker
It is much easier to set the TextColor in Xamarin.Forms:
var picker = new Xamarin.Forms.Picker
{
TextColor = Color.Red
};

Xamarin C# content page not loading image for Android JVM

I have a problem attempting to load an image for the Android JVM in use on Visual Studio 2017 when debugging. Below is a sample of my code:
public class ImageDisplayPage : ContentPage
{
public ImageDisplayPage()
{
Content = new ScrollView
{
Content = new StackLayout()
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children =
{
new Image
{
IsVisible = true,
Aspect = Aspect.AspectFit,
Source = ImageSource.FromResource("Resources.a.png")
}
}
}
};
}
}
I have a folder in my project called "Resources" where the image is supposed to be loaded from, and have followed the path convention used in numerous posts on StackOverFlow and the guide listed here: https://developer.xamarin.com/guides/xamarin-forms/user-interface/images
I use Visual Studio 2017, coding in C# and when I attempt to debug this, the following message is what I get from the debug output:
Image data was invalid: Xamarin.Forms.StreamImageSource
The image in question is an 80kb PNG image.
Thank you in advance for any assistance
You should place your image inside the Resources/drawable folder of your android project and only place the image name and the extension.
public class ImageDisplayPage : ContentPage
{
public ImageDisplayPage()
{
Content = new ScrollView
{
Content = new StackLayout()
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children =
{
new Image
{
IsVisible = true,
Aspect = Aspect.AspectFit,
Source = "a.png"
}
}
}
};
}
}

Convert Xamarin.Forms StackLayout to Android View

I am trying to convert Xamarin.Forms stack layout to Android native View class to use it in IWindowManager.AddView method.
Conversion code is
static class ViewToAndroidViewConverter
{
public static Android.Views.View GetNativeView(this VisualElement view)
{
if (Platform.GetRenderer(view) == null)
Platform.SetRenderer(view, Platform.CreateRenderer(view));
var renderer = Platform.GetRenderer(view);
renderer.Tracker.UpdateLayout();
return renderer.ViewGroup;
}
}
And this is StackLayout that I am trying to convert
StackLayout testView = new StackLayout();
testView.Children.Add(new Label { Text = "Incoming call text" });
testView.Children.Add(new Label { Text = incomingNumber });
testView.BackgroundColor = Color.Green;
windowManager.AddView( testView.GetNativeView(),
new WindowManagerLayoutParams {
Title = "Call title sample",
Gravity = GravityFlags.Center,
Type = WindowManagerTypes.SystemAlert,
Height = 500,
Width = 1080
});
The problem is that this test view is shown, but without label contents (solid green rectangle only).
Is there any way to create an android native view from stack layout with full contents?

Categories