Xamarin Forms Grid Layouts
I'm having a hard time setting the text and images on the grid. Here is what I need to do:
- Two Columns
- First column contains two rows of text, left-aligned.
- Second column contains a single image, occupying the entire height, but right-aligned.
So it would essentially look like this:
I've tried two approaches.
The first approach was creating a 2x2 grid, and setting the ColumnSpan of the image to 2. But the icon was not centered vertically, it was still in the top row.
The second approach was creating a 1x2 grid (1 row, 2 columns), then add a StackLayout containing the two text strings to the first child, and the image to the second child. This time the image was centered vertically, but unfortunately left-aligned.
Can anyone help out, please?
Thank you.
Code for the second approach:
Content = new Grid
{
//Padding = new Thickness(75, 5, 25, 5),
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.StartAndExpand,
RowDefinitions =
{
new RowDefinition(),
},
ColumnDefinitions =
{
new ColumnDefinition(),
new ColumnDefinition(),
},
};
(Content as Grid).RowDefinitions[0].Height = new GridLength(1, GridUnitType.Star);
(Content as Grid).ColumnDefinitions[0].Width = new GridLength(9, GridUnitType.Star);
(Content as Grid).ColumnDefinitions[1].Width = new GridLength(1, GridUnitType.Star);
StackLayout left = new StackLayout
{
HorizontalOptions = LayoutOptions.StartAndExpand,
VerticalOptions = LayoutOptions.Center,
Orientation = StackOrientation.Vertical,
Children =
{
firstName,
lastName,
}
};
StackLayout right = new StackLayout
{
HorizontalOptions = LayoutOptions.Start,
VerticalOptions = LayoutOptions.Center,
Orientation = StackOrientation.Horizontal,
Children =
{
icon,
}
};
(Content as Grid).Children.Add(left, 0, 0);
(Content as Grid).Children.Add(right, 1, 0);
//(Content as Grid).Children[1].HorizontalOptions = LayoutOptions.End
This now looks like this:
The image should be in the far right side of the grid.
Thanks.
1 answer
-
answered 2017-08-16 19:26
Jason
in your #2 example, the "right" StackLayout has HorizontalOptions.Start, which means it will be left aligned. You probably want to have it fill it's container, then right-align the image within it. Or get rid of the StackLayout altogether
See also questions close to this topic
-
WinForm: Find if network connection is metered (network cost)
In a Universal Windows Platform application, there are APIs such as
GetInternetConnectionProfile()
to find out whether a network connection has a cost associated to it, i.e. metered connection.Is there a way a WinForm desktop application can find out if the network connection with active internet is metered connection?
-
I can´t retrieve content-disposition and fileName from headers doing a httprequest.
My final goal is to download the file from server, but I think I´m halfway to the goal. I assume that I nee to change the last lines from the front end for saving the downloaded file. However, the following error is appearing when I check whats on the headers.
From the server side I´m doing the following to send fulfill what I expect from the headers and output the file stream.
[HttpGet, Route("DownloadAttachment")] public async Task<HttpResponseMessage> DownloadAttachment(string fileName) { //Here I previously got the idFromtheFile. FileDTO fileTaskContent = this.taskService.GetFileByIdTaskContent(idFromFile); //fileAWS represents the stream var fileAWS = await _awsService.GetFile(fileTaskContent.PathAWS); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(fileAWS.ResponseStream); response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileTaskContent.Name }; return response; }
Then on my angularjs controller I´m getting the response that called the service that made the request.
function downloadAttachment(fileName) { taskService.downloadAttachment(fileName) // Add p .then(function (response) { if (response.data) { var headers = response.headers(); //Here the heders get an arbitrary value than the one from server without showing content disposition nor filename var contentType = headers['content-type']; var data = new Blob([response.data], {type: contentType}); var url = URL.createObjectURL(data); window.open(url, '_blank'); } }); }
Unfortunately I´m getting the error TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.remoteFunction (:2:14).
Any help or ideas are really appreciated!
-
C# Dynamically set sound output of application
A while back I was working on an application that controls the sound output of programs based on which screen the program is. For example I have a browser on my TV and by that I want to set the sound output of the program to the TV's speakers. I've already done the detection part (find on which screen the program is) and I'm ready to implement any solutions you give me here. My program works by always following the application that is focused, so if it changes screens it should change sound output
As I told you above, I already have the screen detection done but when it comes to changing the sound output for only that application that is focused I had no luck so far. How do I accomplish this? Is it possible? I've already searched on this topic and found libraries that should do this like NAudio but none of them seemed to work for me, that's why I stopped developing this program, until now :)
Any help would be appreciated and please don't down vote without telling me what the mistake or problem is so I can fix it.
-
How to animate a kivy layout subclass?
I am subclassing
kivy.uix.layout
. The goal is to animate the child widgets by recalculating their position on each frame.What’s the correct way of doing this?
I can schedule a re-layout by doing this:
self.layout_clock = Clock.schedule_interval(self._trigger_layout, -1)
But I get lots of errors:
[CRITICAL] [Clock ] Warning, too much iteration done before the next frame. Check your code, or increase the Clock.max_iteration attribute
I guess by changing the childrens’ positions inside of
do_layout
, I triggerdo_layout
again by some event binding and thus create an infinite loop, right?So how do I do this?
-
Coloring same node groups in Cytoscape and their edges automatically
How to automatically colored the same group nodes (not manually) in Cytoscape? Example: I have a group of students linked to two universities, I want to color the students linked to the first university with a color and shape different than the other students that are linked to the second university. Also, I want to color the edge between them in a color and all this automatically not by selecting them. Also, I have another question, what type does the Cytoscape take in the select tab(filter)?
-
How to switch to another workflow layout in Visual Studio 2017?
After installing, when starting Visual Studio for the first time, it asks what kind of development you're going to do and offers different layout templates for windows, toolbars like "web development", "desktop development" etc.
Is there a way to switch to one of these profiles after initially choosing the wrong one? I know, I can arrange everything by hand, but that would take a while. Maybe you need to delete a settings file somewhere so that VS asks again?
-
Set the EditText ImeAcionLabel to custom text?
Currently, I'm looking to change the design of the
button
that closes theAndroid keyboard
. Currently it looks like: Basic Android Keyboard. I want to remove the checkmark and replace it with some text like OK or Done without changing the whole keyboard.Using
ImeOptions
, I know i can set theAndroid.Views.InputMethods.ImeAction
to a default icon, but none of the default icons are what I'm looking for.Using
SetImeActionLabel("OK", Android.Views.InputMethods.ImeAction.Done)
, I can edit thetext
that's being shown, but it's only text. It looks the green,circular background
. If I go with this route, I'm unsure on how I can edit the styles of thisActionLabel
. Here is a picture for reference: Android Keyboard with OK.I'm having a lot of trouble finding a similar example or problem and can't exactly solve it myself.
-
How to compress(Zip) a video in xamarin forms
I want to compress a large sized video and upload it into the server.How can I do this, I have no idea about this.
Please help me....
-
Xamarin ContentView Constructors
I am creating a subclass of ContentView,
UserPostView
to use as a data template in a ListView. I dynamically add items to the ItemSource of ListView by creating new instances ofUserPostView
.<Image x:Name="PictureView" Source="Logo" BackgroundColor="#ddd" /> <Label x:Name="NameView" Text="Name" TextColor="#444" FontAttributes="Bold" Grid.Row="0" Grid.Column="1" Margin="10" /> <Label x:Name="LocationNameView" Text="Location" TextColor="#666" Grid.Row="0" Grid.Column="2" YAlign="Center" /> <Label x:Name="DeptNameView" Text="Dept" TextColor="#666" Grid.Row="0" Grid.Column="3" YAlign="Center" />
and in code:
using System; using System.Collections.Generic; using Xamarin.Forms; namespace CMCityClient.Views { public partial class UserPostView : ContentView { public ImageSource Picture { get { return PictureView.Source; } set { PictureView.Source = value; } } public string PostOwner { get { return NameView.Text; } set { NameView.Text = value; } } public string PostOwnerLocation { get { return LocationNameView.Text; } set { LocationNameView.Text = value; } } // ... // ... public UserPostView(ImageSource picture, string owner, string loc, string dept, string text) { InitializeComponent(); Picture = picture; PostOwner = owner; PostOwnerLocation = loc; PostOwnerDept = dept; PostText = text; } public UserPostView(ImageSource picture, string owner, string loc, string dept, string text, ImageSource image) { InitializeComponent(); Picture = picture; PostOwner = owner; PostOwnerLocation = loc; PostOwnerDept = dept; PostText = text; PostImage = image; } } }
but when I use it in my ListView, it will not show the passed data, it shows the original data instead. (Text="Name"...)
public TimelinePage() { InitializeComponent(); ImageSource pic = ImageSource.FromUri(new Uri("https://tse1.mm.bing.net/th?id=OIP.acchQ02P8HmrmwbjCTwG5AHaHa&pid=Api")); timeline.ItemsSource = new UserPostView[]{ new UserPostView(ImageSource.FromResource("Logo"), "Kevin Wang", "SHDR", "AOP", "hey"), new UserPostView(pic, "Lily", "SHDR", "ENT", "good"), new UserPostView(pic, "Zhang Shuo", "FRDL", "ENT", "Salut! "), }; }
help! How can I let them show the data that passed through the constructor?
-
oncaplaythrough of multiple videos (grid)
I am trying to figure out a way of playing back videos only after all 4 have loaded to a canplaythrough state. I was thinking of nesting functions to then come to a playClass function like below
var classVideos = document.getElementsByClassName("playbackVideos"); playVideos(){ for(i=0; i<classVideos.length; i++){ classVideos[i].play(); } } loadVideos(){ classVideos[0].oncanplaythrough = function(){ classVideos[1].oncanplaythrough = function(){ classVideos[2].oncanplaythrough = function(){ classVideos[3].oncanplaythrough = function(){ playVideos(); } } } } }
The loadVideos() function would be called by a play button or eventListener on a seekbar with "mouseup".
Any help would be greatly appreciated.
-
how to drag and move child views in Grid to swap their positions
I've searched some days but didn't get a good solution. I'm developing an Xamarin.iOS project, which uses Grid to arrange several views.
What I want is to drag and move one child view to another place to swap the positions of both views. For example, if I have 2 rows and 2 columns, let's call them view 0, 1, 2, 3. If I drag view 0 to view 2, then view 0 and 2 will swap their positions.
I first tried to use dragInteraction and dropInteraction, but by tests, it's not really moving the child view when dragging, just moving some provided data.
But search, I found some solutions for dragging and moving inside ListView. But seems ListView doesn't support multiple columns.
Could someone give me some clues to this? Very appreciate that. BTW, the child view I want to drag is an UIView playing video using AVPlayer.
-
Bootstrap grip in mobile view and Desktop view
<div class="container-fluid"> <div class="row"> <div class="col-xs-8 col-md-8 col-sm-8"> <img src="#"/> </div> <div class="col-xs-4 col-md-4 col-sm-4"> <blockquote> <p style="font-size:20px; color:black;">"I had never seen anything in the least like them before. A single look at them is enough to show that they could only be written by a mathematician of the highest class. They must be true because, if they were not true, no one would have the imagination to invent them."</p> <footer><cite>Anonymous</cite></footer> </blockquote> </div> </div>
Hi in the above code I am trying make the text and image side by side and I am getting the expected output while viewing in desktop but the same page when viewed in mobile I see part of text and image getting overlapped but the same page is ok when viewed in mobile in desktop view.
How would I sync the appearance in all view together?
Any pointers will be helpful.
Thanks.
PS: I dont have enough reps to post the image so #'ing the img src value between quotes
-
XAML UWP Stackpanel size relative to screen size
I am building a UWP app that displays weather data. Currently I am working on a
dataTemplate
that is being used within a pivotI am unable to get the Stackpanels width to size relative to the screen size (or their parent container) and unable to center them, I would also like to set a margin each side relative to the screen size (as I,ve done at ease before with html).
Also is it possible to have the image as a background to each stackpanel or display it beside the data as I am getting
Error: "The property 'VisualTree' is set more than once"
?I have checked all the other posts available on this but cannot yet find a solution
<Page.Resources> <DataTemplate x:Name="ListViewDataTemplate" > <StackPanel BorderBrush="Black" BorderThickness="2" Margin="2" HorizontalAlignment="Center" Width="500" Background="DeepSkyBlue"> <Image Source="{Binding icon}" Stretch="Fill" Height="100" Width="150"></Image> <StackPanel Orientation="Horizontal" > <TextBlock HorizontalAlignment="Stretch" FontWeight="Bold" Text="Temperature: " ></TextBlock> <TextBlock HorizontalAlignment="Stretch" Text="{Binding temp}"></TextBlock> </StackPanel> <StackPanel Orientation="Horizontal"> <TextBlock Text="Time : " FontWeight="Bold"></TextBlock> <TextBlock Text="{Binding dtime}"></TextBlock> </StackPanel> <StackPanel Orientation="Horizontal"> <TextBlock Text="Description : " FontWeight="Bold"></TextBlock> <TextBlock Text="{Binding desc}"></TextBlock> </StackPanel> <StackPanel Orientation="Horizontal"> <TextBlock Text="Humidity : " FontWeight="Bold"></TextBlock> <TextBlock Text="{Binding humidity}"></TextBlock> </StackPanel> <StackPanel Orientation="Horizontal"> <TextBlock Text="Windspeed : " FontWeight="Bold"></TextBlock> <TextBlock Text="{Binding windSpeed}"></TextBlock> </StackPanel> </StackPanel> </DataTemplate> </Page.Resources>
-
C# UWP Adding scrollbar,margin,border to pivotItem
I am creating Windows UWP app that displays weather forecasts from a nestedlist
sortedDays
. It contains days on the Outer list and hourly forecasts in the inner list. (using pivot)I am trying to display in each pivotItem, a separate stackPanel for every hourly forecast so that eachpivotItem
will have numerous stackPanels of hourly forecast.Unfortunately my data is running off the bottom of the screen and I cannot seem to get a scroll bar working. I have also been struggling with adding any form of margin or boarder around the
hourStack
stackPanels. As the data is is coming from a nested list generated from an API I feel it must be added through c# code and not xaml(open to opinions). I have looked up the documentation but cant find anything that works through c#//dynamically add a pivot item PivotItem pvt; ScrollViewer scroll; //loop through SortedDays to seperate Day and hour forecasts int xCount = 0, yCount = 0; foreach (var sd in myForecast.SortedDays) {// Define a ScrollViewer scroll = new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Visible }; pvt = new PivotItem { Header = myForecast.SortedDays[xCount][0].dayOfWeek }; var dayStack = new StackPanel(); foreach (var sh in sd) { var hourStack = new StackPanel { HorizontalAlignment = HorizontalAlignment.Center }; var timeBlock = new TextBlock { Text = myForecast.SortedDays[xCount][yCount].dtime, FontSize = 30 }; hourStack.Children.Add(timeBlock); var tempBlock = new TextBlock { Text = "Tempeture (c)\t:" + System.Convert.ToString(Math.Truncate((myForecast.SortedDays[xCount][yCount].temp - 273.15) * 100) / 100) }; hourStack.Children.Add(tempBlock); var descBlock = new TextBlock { Text = myForecast.SortedDays[xCount][yCount].desc }; hourStack.Children.Add(descBlock); var windBlock = new TextBlock { Text = "Windspeed\t:" + System.Convert.ToString(myForecast.SortedDays[xCount][yCount].windSpeed) }; hourStack.Children.Add(windBlock); var humBlock = new TextBlock { Text = "Humidity\t:" + System.Convert.ToString(myForecast.SortedDays[xCount][yCount].humidity) }; hourStack.Children.Add(humBlock); // append hourStack to dayStack yCount++; dayStack.Children.Add(hourStack); } scroll.Content = dayStack; // set dayStack as pivots content pvt.Content = scroll; // add pivotItem to pivot pvtWeather.Items.Add(pvt); pvt = null; xCount++; yCount = 0; }
WeatherPage.xaml
<Page x:Class="WeatherForecast.WeatherPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:WeatherForecast" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Pivot x:Name="pvtWeather" Margin="100,100,100,100" Height="1200" HorizontalAlignment="Center" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.BringIntoViewOnFocusChange="True"> </Pivot> </Grid>
-
WPF - StackPanel Hide Content to Left
I'm trying to insert an list of button in a StackPanel But I'd like to hide the wrap content to left instead of right, as it is currently doing
Here my is code xaml
<StackPanel Orientation="Horizontal" > <Button Width="50">1.5678</Button> <Button Width="50">1.5678</Button> <Button Width="50">1.5678</Button> <Button Width="50">1.5678</Button> <Button Width="50">1.5678</Button> <Button Width="50">1.5678</Button> <Button Width="50">1.5678</Button> <TextBox x:Name="EDT_NUMERO_CFOP" Style="{StaticResource TextBoxNoBorder}" Height="30"></TextBox> </StackPanel>
I think that there's something like "hideToLeft"