PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label xaml. Show all posts
Showing posts with label xaml. Show all posts

Monday, November 21, 2022

[FIXED] How to bind a method for custom dependency property via user control?

 November 21, 2022     c#, visual-studio, windows, winui-3, xaml     No comments   

Issue

I currently have a Button inside my custom UserControl that needs to have a method name binded to it's Click dependency, the method name being provided from a custom dependency property in the user control. Any ideas on how to do this?

Page.xaml

<local:CustomButton OnClick="CustomButton1_Click" ... />

Page.xaml.cs

private void CustomButton1_Click(object sender, RoutedEventArgs e)
{
    // do something...
}

CustomButton.xaml

<Button Click={x:Bind OnClick} ... />

CustomButton.xaml.cs

public sealed partial class CustomButton : UserControl
{
   ...
   
   public static readonly DependencyProperty OnClickProperty = DependencyProperty.Register("OnClick", typeof(string), typeof(CustomButton), new PropertyMetadata(true));
    
   public bool IsNavigator
   {
       get => (string)GetValue(OnClickProperty);
       set => SetValue(OnClickProperty, value);
   }
}

Solution

Do you mean you want to call CustomButton1_Click when CustomButton is clicked?

CustomButton.xaml

<UserControl
    x:Class="UserControls.CustomButton"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UserControls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid>
        <Button Content="Button" Click="Button_Click"/>
    </Grid>
</UserControl>

CustomButton.xaml.cs

using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;

namespace UserControls;

public sealed partial class CustomButton : UserControl
{
    public CustomButton()
    {
        this.InitializeComponent();
    }

    public event EventHandler? OnClick;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        OnClick?.Invoke(this, EventArgs.Empty);
    }
}

And use it like this:

<Grid>
    <local:CustomButton OnClick="CustomButton_OnClick" />
</Grid>


Answered By - Andrew KeepCoding
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to bind a List of colors to property that requires Brush?

 November 21, 2022     c#, data-binding, visual-studio, winui-3, xaml     No comments   

Issue

I've spent all day trying to figure out how I can simply have a list of colors (for example: Colors.AliceBlue) as my ItemsSource for a GridView and bind those colors to a Fill property of a Rectangle inside the DataTemplate. I know the Fill property must be a brush, so I have tried using a converter to convert the color to a SolidColorBrush, but it has not worked. I've also tried not using a converter and instead changing the List to List but that did not work either. No matter what I do, I keep getting binding errors that say:

Converter failed to convert value of type '#FFF0F8FF' to type 'Brush'. Binding: Path='' DataItem='#FFF0F8FF'; target element is 'Microsoft.UI.Xaml.Shapes.Rectangle' (Name='null'); target property is 'Fill' (type 'Brush')

Everything I try always seems to return my color as an ARGB, in this case "#FFF0F8FF", which is not what the property accepts. Any ideas on how to bind my list of colors to my item/data template? I definitely want to use color names in my list, as it is easier to access colors this way rather than looking up their RGB codes and whatnot.


Page.xaml

<GridView ItemsSource="{x:Bind ColorOptions}" IsItemClickEnabled="True" SelectionMode="Single">
    <GridView.ItemTemplate>
        <DataTemplate>
            <Rectangle Fill="{Binding}" Width="40" Height="40" />
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

Page.xaml.cs

using System.Windows.Media;
...
public readonly List<Color> ColorOptions = new()
{
    Colors.AliceBlue,
    Colors.Black,
    Colors.DarkBlue,
    Colors.Brown,
    Colors.DarkGreen,
    Colors.Magenta
};

Also, if you're interested, here's the converter I created and tried, but also did not work.

BrushConverter.cs

using System.Windows.Media;
using Microsoft.UI.Xaml.Data;

namespace App.Helpers;

public class BrushConverter : IValueConverter
{
    public object? Convert(object value, Type targetType, object parameter, string language)
    {
        return new SolidColorBrush((Color)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return ((SolidColorBrush)value).Color;
    }
}

Page.xaml (using converter)

<GridView ItemsSource="{x:Bind ColorOptions}" IsItemClickEnabled="True" SelectionMode="Single">
    <GridView.ItemTemplate>
        <DataTemplate>
            <Rectangle Fill="{Binding Converter={StaticResource BrushConverter}}" Width="40" Height="40" />
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

Solution

This way you don't need a converter:

using Microsoft.UI;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using System.Collections.Generic;
using Windows.UI;

namespace GridViews;

public class ColorOption
{
    public ColorOption(string name, Color color)
    {
        Name = name;
        Color = new SolidColorBrush(color);
    }

    public string Name { get; set; }

    public Brush Color { get; set; }
}

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    public List<ColorOption> ColorOptions { get; } = new()
    {
        new ColorOption("Alice Blue", Colors.AliceBlue),
        new ColorOption("Black", Colors.Black),
        new ColorOption("Dark Blue", Colors.DarkBlue),
        new ColorOption("Brown", Colors.Brown),
        new ColorOption("Dark Green", Colors.DarkGreen),
        new ColorOption("Magenta", Colors.Magenta),
    };
}
<GridView
    IsItemClickEnabled="True"
    ItemsSource="{x:Bind ColorOptions}"
    SelectionMode="Single">
    <GridView.ItemTemplate>
        <DataTemplate x:DataType="local:ColorOption">
            <StackPanel>
                <TextBlock Text="{x:Bind Name}" />
                <Rectangle
                    Width="40"
                    Height="40"
                    Fill="{x:Bind Color}" />
            </StackPanel>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>


Answered By - Andrew KeepCoding
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, November 18, 2022

[FIXED] How can I vertically align a TableCell (or its content) of a FlowDocument

 November 18, 2022     flowdocument, vertical-alignment, wpf, xaml     No comments   

Issue

Is there any way to align the content of a TableCell to the bottom? I thought this was easy, but obviously, it is not.

The situation:

Inside a FlowDocument I have the following (simplified) Table:

<Table>
    <Table.Columns>
        <TableColumn Width="Auto"/>
        <TableColumn Width="Auto"/>
        <TableColumn Width="Auto"/>
    </Table.Columns>
    <TableRowGroup>
        <TableRow>
            <TableCell>
                <BlockUIContainer>
                    <Image Source="{Binding to an image}"/>
                </BlockUIContainer>
            </TableCell>
            <TableCell containing something else/>
           <TableCell>
                <BlockUIContainer>
                    <Image Source="{Binding to another image}"/>
                </BlockUIContainer>
            </TableCell>
        </TableRow>
    </TableRowGroup>
</Table>

The two images do not have the same height so there is some empty space below the smaller of them.

What I want:

Instead, I want the empty space above the smaller image (i.e. the images aligned to the bottom of the TableRow).

What I tried:

I tried to find a VerticalAlignment property to change the alignment. However, there is no VerticalAlignment property in BlockUIContainer, TableCell or TableRow.

Also, I tried replacing the BlockUIContainer by an InlineUIContainer and setting its BaselineAlignment. However, to do this, I had to wrap it into a Paragraph like so:

<TableCell>
    <Paragraph>
        <InlineUIContainer BaselineAlignment="Bottom">
            <Image Source="{Binding to an image}"/>
        </InlineUIContainer>
    </Paragraph>
</TableCell>

Now I have an image aligned to the bottom of a Paragraph which is aligned to the top of the TableCell and only as high as required for the Image. So it looks exactly as it did before.


Solution

The only way to do this in my experience is to use a grid to format an entire table row. Use the grid to create columns, not the table. Therefore you can use the capabilities of the grid to bottom align your images. Here is what your table might look like now...

    <Table>
        <TableRowGroup>
            <TableRow>
                <TableCell>
                    <BlockUIContainer>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition/>
                                <ColumnDefinition/>
                                <ColumnDefinition/>
                            </Grid.ColumnDefinitions>
                            <Image Grid.Column="0" Source="Images/globe.png" Height="10" Width="10" VerticalAlignment="Bottom"/>
                            <TextBlock Grid.Column="1" TextWrapping="Wrap">This is something else</TextBlock>
                            <Image Grid.Column="2" Source="Images/globe.png" Height="20" Width="20" VerticalAlignment="Bottom"/>
                        </Grid>
                    </BlockUIContainer>
                </TableCell>
            </TableRow>
        </TableRowGroup>
    </Table>


Answered By - AQuirky
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, November 17, 2022

[FIXED] How can I Expand Items Horizontally & Verticially within two Colums using an XML?

 November 17, 2022     multiple-columns, vertical-alignment, xaml, xml     No comments   

Issue

I am trying to expand items down two columns within a Grid. Only the Last Two Buttons show. How can I "seperate" them down the column?

I have spent two days trying to get this right, I am new to this, but i don't think it would be that difficult?

When i remove the ScrollViewer ie; "VertcialAlignment="Top" It just Expands the Two Buttons All the way down the two columns, I have tried adding Orientation to the Grid.RowDefinition, etc. It has not worked. Thank you for any help.

here is code:

<telerik:GroupBox Header="{x:Static res:UXResources.Panel_CustomPanel_Title}">
        <ScrollViewer VerticalScrollBarVisibility="Auto"
                      HorizontalScrollBarVisibility="Disabled"
                      CanContentScroll="True"
                      VerticalAlignment="Top">
<Grid>
<Grid.ColumnDefinitions>
    <ColumnDefinition />
     <ColumnDefinition />
</Grid.ColumnDefinitions>

<Grid Grid.Column="1">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
         <ColumnDefinition />
    </Grid.ColumnDefinitions>


    <Grid.RowDefinitions>
        <RowDefinition  Height="Auto"/>
        <RowDefinition  Height="Auto"/>
        <RowDefinition  Height="Auto"/>
        <RowDefinition  Height="Auto"/>
    </Grid.RowDefinitions>
</Grid>

            <telerik:RadButton     FontWeight="800"      
                                   Background="LightGreen"
                                   Grid.Row="0" 
                                   Grid.Column="0" 
                                   Grid.ColumnSpan="1"
                                   Command="{Binding Item_AddCommand}"
                                   CommandParameter="PB">
                    Button One
            </telerik:RadButton> 

            <telerik:RadButton     FontWeight="400"    
                                   Background="Orange"
                                   Grid.Row="0" 
                                   Grid.Column="1" 
                                   Grid.ColumnSpan="2"
                                   Command="{Binding Item_AddCommand}"
                                   CommandParameter="1LP">
                    Button Two
             </telerik:RadButton>

             <telerik:RadButton FontWeight="400"    
                                   Background="Orange"
                                   Grid.Row="1"
                                   Grid.Column="0"
                                   Grid.ColumnSpan="1"
                                   Command="{Binding Item_AddCommand}"
                                   CommandParameter="2LP">
                    Button Three
              </telerik:RadButton>

              <telerik:RadButton   FontWeight="400"    
                                   Background="Orange"
                                   Grid.Row="1"
                                   Grid.Column="1"
                                   Grid.ColumnSpan="2" 
                                   Command="{Binding Item_AddCommand}"
                                   CommandParameter="3LP">
                    Button Four
              </telerik:RadButton>


    </ScrollViewer>
</telerik:GroupBox>

Here is an image of what i am doing. enter image description here

Sorry, i guess i can't embed pics yet. nonetheless, it just shows the columns with two buttons that stay at top.. instead of the four spread across evenly.


Solution

Can you draw something and post what your goal is ?

I'm not sure of the result you want.

All I can see and say is that your items are not in the grid. You close the </Grid> too soon: close the grid just above the </ScrollViewer>. Otherwise, they are put inside the first grid which only contains 2 columns and no rows definitions (so just 1). It result that where buttons are stacked above each other. The last one being the visible one. Your second Grid contains nothing expect definitions of columns and rows, but it has 0 child so it is useless.

You don't need to set Grid.Column=0 or Grid.ColumnSpan=0 because its the default value. If you put something if the second column: Grid.Column=1 (0 based index) and there is only 2 columns, the Grid.ColumSpan=2 is pointless because 1 (col index)+2 (col to take) = 3 columns needed when you only have one.

Having said that, make sure your buttons have an HorizontalAlignment and VerticalAlignment set to Stretch to fill the space.

You can create an implicit style or explicit one to factorize the duplicated code on each button.



Answered By - Nk54
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, September 14, 2022

[FIXED] How to delete an Item selected form ListView in Xamarin

 September 14, 2022     button, cross-platform, listview, xamarin.forms, xaml     No comments   

Issue

I'm building a Xamarin CrossPlatform App!

App contains 2 pages : HomePage, DetailGetData

HomePage: This page contains a ListView which is displaying list of data form webapi in cells and whenever I clicked each cell it goes to DetailGetDatapage which shows the detail of that data.

Problem: Now the problem is that I wanted to delete that selected item from DetailGetData page. A DeleteButton is placed and when i press that button that details and selected item should be deleted from the ListView as well. How it is possible ?

ScreenShot DetailGetData :https://i.stack.imgur.com/TXg4G.png

ScreenShot HomePage : https://i.stack.imgur.com/g1Hn1.png

Code:

DetailGetData Xaml:

 <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Last_MSPL.Views.DetailGetData">

    <StackLayout HorizontalOptions="Center" VerticalOptions="Center">

        <Label Text="{Binding employee_name}" x:Name="empname" FontSize="Medium" FontAttributes="Bold" />
        <Label Text="{Binding employee_age}" x:Name="age" FontSize="Medium" FontAttributes="Bold" />
        <Label Text="{Binding employee_salary}" x:Name="salary" FontSize="Medium" FontAttributes="Bold" />

        <Button x:Name="DeleteItem" Text="Delete" Clicked="DeleteItem_Clicked"  />
    </StackLayout>

</ContentPage>

HomePage Xaml:

    <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Last_MSPL.HomePage">


    <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <ListView x:Name="Demolist" ItemSelected="OnItemSelected" BackgroundColor="White">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell Height="100">
                        <ViewCell.ContextActions>
                            <MenuItem x:Name="OnMore" Clicked="OnMore_Clicked" CommandParameter="{Binding .}"
                                 Text="More" />
                            <MenuItem x:Name="OnDelete" Clicked="OnDelete_Clicked" CommandParameter="{Binding .}"
                                 Text="Delete" IsDestructive="True" />
                        </ViewCell.ContextActions>
                        <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Padding="30,0">

                            <Label Text="{Binding employee_name}" FontAttributes="bold" FontSize="Small" TextColor="Black" x:Name="en"/>
                            <Label Text="{Binding employee_age}" FontSize="Micro" TextColor="Black" FontAttributes="Italic"/>
                            <Label Text="{Binding id}" IsVisible="False" />


                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <ImageButton Source="fedit.png" 
            BackgroundColor="Transparent"
            AbsoluteLayout.LayoutFlags="PositionProportional"  
            AbsoluteLayout.LayoutBounds=".95,.95,55,55" 
            Clicked="ImageButton_Clicked">
        </ImageButton>

    </AbsoluteLayout>
</ContentPage>

HomePage.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Last_MSPL.MenuItems;
using Last_MSPL.Views;
using System.Collections;

namespace Last_MSPL
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HomePage : ContentPage
    {
        public IEnumerable ObjOrderList { get; private set; }


        public HomePage()
        {
            ((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            InitializeComponent();
            Get();
        }



        public async void Get()
        {
            HttpClient client = new HttpClient();
            try
            {
                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var totalCount = ObjOrderList.Count;
                Demolist.ItemsSource = ObjOrderList.GetRange(0, 40);
            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            HttpClient client = new HttpClient();
            if (Demolist.SelectedItem != null)
            {

                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var abc = (GetData)e.SelectedItem;

                GetData data = new GetData();
                data = ObjOrderList.ToList().Where(x => x.id == abc.id).FirstOrDefault();

                var detailPage = new DetailGetData(data);
                detailPage.BindingContext = e.SelectedItem as GetData;
                Demolist.SelectedItem = null;
                await Navigation.PushModalAsync(detailPage);

            }
        }

DetailGetData.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Last_MSPL.MenuItems;

namespace Last_MSPL.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DetailGetData : ContentPage
    {
        public DetailGetData(GetData _data)
        {
            InitializeComponent();
            BindingList(_data);

        }



        public void BindingList(GetData data)
        {
            empname.Text = data.employee_name;
            age.Text = data.employee_age;
            salary.Text = data.employee_salary;
        }


        public async void DeleteItem_Clicked(object sender, EventArgs e)
        {





            await Navigation.PopModalAsync();
        }
    }
}

Solution

You can realize the function of deleting the item by adding a static datasouce class. And set the Demolist.ItemsSource = DataSource.collection; When click delete button in DetailGetData page, modify the Demolist.ItemsSource by deleting the item. So the code is like this:

DataSource.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace App10
{
    public static class DataSource
    {
        public static ObservableCollection<GetData> collection;

        static DataSource()
        {
        }
        public static void persist(List<GetData> collection)
        {
            //do something here
        }

        public static void initializeData(List<GetData> listdata)
        {
            collection = new ObservableCollection<GetData>(listdata);
        }
    }
}

MainPage.xaml.cs

[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MainPage : ContentPage
    {
        List<GetData> dataList;
        public MainPage()
        {
            //((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            InitializeComponent();
            Get();
            //RefreshList();
        }
        public async void Get()
        {
            HttpClient client = new HttpClient();
            try
            {
                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var totalCount = ObjOrderList.Count;

                dataList = ObjOrderList.GetRange(0, 40);
                DataSource.initializeData(dataList);
                Demolist.ItemsSource = DataSource.collection;

            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            HttpClient client = new HttpClient();
            if (Demolist.SelectedItem != null)
            {

                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var abc = (GetData)e.SelectedItem;

                GetData data = new GetData();
                data = ObjOrderList.ToList().Where(x => x.id == abc.id).FirstOrDefault();

                var detailPage = new DetailGetData(data);
                detailPage.BindingContext = e.SelectedItem as GetData;
                Demolist.SelectedItem = null;
                await Navigation.PushModalAsync(detailPage);

            }
        }
}

DetailGetData.xaml.cs

   [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DetailGetData : ContentPage
    {
        public GetData thisData;

        public DetailGetData(GetData _data)
        {
            InitializeComponent();
            BindingList(_data);
            thisData = _data;

        }


        public void BindingList(GetData data)
        {
            empname.Text = data.employee_name;
            age.Text = data.employee_age;
            salary.Text = data.employee_salary;
        }


        public async void DeleteItem_Clicked(object sender, EventArgs e)
        {

            GetData toberemoveditem = (from item in DataSource.collection
                                       where item.id == thisData.id
                             select item)
                            .FirstOrDefault<GetData>();
            DataSource.collection.Remove(toberemoveditem);


            await Navigation.PopModalAsync();
        }
    }


Answered By - AbbyWang - MSFT
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 13, 2022

[FIXED] How to display data in Cells View using Xamarin

 September 13, 2022     api, cross-platform, user-interface, xamarin.forms, xaml     No comments   

Issue

I'm building a CrossPlatform App in Xamarin!

I'm getting data from Web Api and it's working fine, the problem is that the data is showing in ListView like columns but I wanted to display that data in Cells View so I can add functionalities like left and right swipeand I don't know how to do this.

My current XAML UI:

    <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="LastTry.Attendance">


    <ListView x:Name="selectOrd" RowHeight="50" SeparatorColor="White" 
                  HasUnevenRows="True">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell >
                    <StackLayout   Orientation="Horizontal"  >
                        <StackLayout Orientation="Horizontal" VerticalOptions="Center">
                            <Label  Text="{Binding id}" Font="9" TextColor="Black" />
                        </StackLayout>
                        <StackLayout HorizontalOptions="FillAndExpand"  x:Name="employee_name" VerticalOptions="Center"  >
                            <Label  Text="{Binding employee_name}" Font="9" TextColor="Black"   FontAttributes="Bold" HorizontalTextAlignment="Center"/>
                        </StackLayout>
                        <StackLayout HorizontalOptions="FillAndExpand"  x:Name="employee_salary" VerticalOptions="Center"  >
                            <Label  Text="{Binding employee_salary}" Font="9" TextColor="Black"   FontAttributes="Bold" HorizontalTextAlignment="Center"/>
                        </StackLayout>
                        <StackLayout HorizontalOptions="FillAndExpand"  x:Name="employee_age" VerticalOptions="Center"  >
                            <Label  Text="{Binding employee_age}" Font="9" TextColor="Black"   FontAttributes="Bold" HorizontalTextAlignment="Center"/>
                        </StackLayout>
                        <StackLayout HorizontalOptions="FillAndExpand"  x:Name="profile_image" VerticalOptions="Center"  >
                            <Label  Text="{Binding profile_image}" Font="9" TextColor="Black"   FontAttributes="Bold" HorizontalTextAlignment="Center"/>
                        </StackLayout>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

</ContentPage>

Here is an example how I want it:

enter image description here


Solution

Here is the code for the listview same as above:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MSPL.Views.HomePage">

<AbsoluteLayout>

    <ListView x:Name="Demolist" BackgroundColor="White" ItemSelected="Demolist_ItemSelected">

        <ListView.ItemTemplate>
            <DataTemplate>

                <ImageCell Height="30"
                            Text="{Binding employee_name }"
                       Detail="{Binding employee_age}"
                        ImageSource="falto.png">

                    <ImageCell.ContextActions>
                        <MenuItem x:Name="OnMore" Clicked="OnMore_Clicked" CommandParameter="{Binding .}"  Text="More" />
                        <MenuItem x:Name="OnDelete" Clicked="OnDelete_Clicked" CommandParameter="{Binding .}" Text="Delete" IsDestructive="True" />
                    </ImageCell.ContextActions>
                </ImageCell>

            </DataTemplate>
        </ListView.ItemTemplate>

    </ListView>

    <ImageButton Source="images.png" 
        BackgroundColor="Transparent"
        AbsoluteLayout.LayoutFlags="PositionProportional"  
        AbsoluteLayout.LayoutBounds=".95,.95,55,55"   
        Clicked="ImageButton_Clicked"
    />
</AbsoluteLayout>



Answered By - Hashir Malik
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to show all the content of list view row

 September 13, 2022     c#, cross-platform, listview, xamarin.forms, xaml     No comments   

Issue

I am working with Xamarin forms in order to make a crossplatform APP.

I am using a list view but I can't figure how to make a row show it's full content enter image description here

I tried to add HasUnevenRows="True" but didn't do the trick. I also tried to fix RowHeight="100"

Can someone please help me.


Solution

<ListView RowHeight="100" x:Name="ContextDemoList">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
         <StackLayout Padding="5">
              <Label VerticalOptions="CenterAndExpand" Text="{Binding title}" />
         </StackLayout>
      </ViewCell>
         </DataTemplate>
       </ListView.ItemTemplate>
     </ListView>


Answered By - Ufuk Zimmerman
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to create a custom font size in xaml using Xamarin, so that you can change font sizes depending on device?

 September 13, 2022     c#, cross-platform, uwp, xamarin, xaml     No comments   

Issue

Is there are way to create a custom fontsize that would work the same as Micro or Small or Title that are already built into Xamarin. I want to be able to use it like the following:

<Label Text="Test" FontSize="MyFontSize"/>

I think it would be implemented something like the following inside my resource dictionary but it isn't working:

<FontSize x:Key="MyFontSize">
    <OnPlatform x:TypeArguments="FontSize">
        <On Platform="UWP">25</On>
        <On Platform="iOS">12</On>
    </OnPlatform>
</FontSize>

The error says:

"The type FontSize can not be found"

It's not a runtime error. It's just a green underline in the XAML editor.

Can it be done?


Solution

You need to use x:Double instead:

<OnPlatform x:Key="MyFontSize" x:TypeArguments="x:Double">
    <On Platform="UWP">25</On>
    <On Platform="iOS">12</On>
</OnPlatform>

And then reference the resource like this:

<Label Text="Test" FontSize="{StaticResource MyFontSize}"/>

Or you can specify it directly on the view:

<Label Text="Test">
   <Label.FontSize>
      <OnPlatform x:TypeArguments="x:Double">
          <On Platform="UWP">25</On>
          <On Platform="iOS">12</On>
      </OnPlatform>
   </Label.FontSize>
</Label>


Answered By - Martin Zikmund
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, September 12, 2022

[FIXED] how to populate a collectionview defined inside a caruselpage Xamarin.Forms

 September 12, 2022     c#, cross-platform, xamarin.forms, xaml     No comments   

Issue

I have a CaruselPage and inside the DataTemplate I have put a CollectionView

<CarouselPage.ItemTemplate>
    <DataTemplate>
        <ContentPage>

            <ContentPage.Content>


                            <StackLayout>
                                <CollectionView   

                ItemsSource="{Binding Cards}"

                                 VerticalOptions="CenterAndExpand"   
                                 HorizontalOptions="Center"   


                                 EmptyView="Non ci sono Card Formazione"  
                                 Margin="10"
                 x:Name="CV"


     >
                                    <CollectionView.ItemsLayout>
                                        <GridItemsLayout Orientation="Vertical" Span="1" />
                                    </CollectionView.ItemsLayout>
                                    <CollectionView.ItemTemplate>
                                        <DataTemplate>
                                            <Frame BorderColor="Black">
                                                <StackLayout>

                                                    <Label Text="{Binding DisciplinaCard}" Style="{StaticResource LabelTesStyle}"/>
                                                    <Label Text="{Binding DataCard}" Style="{StaticResource LabelTesStyle}"/>
                                                </StackLayout>
                                            </Frame>

                                        </DataTemplate>
                                    </CollectionView.ItemTemplate>
                                </CollectionView>
                            </StackLayout>
                        </StackLayout>



            </ContentPage.Content>
        </ContentPage>
    </DataTemplate>
</CarouselPage.ItemTemplate>

I manage to populate the carusel page but I can't find how to populate the collection view. All the solution that I find is for UWP, but I need to do this in xamarin.forms cross platform.


Solution

According to your description, you want to add collectionview control in CaruselPage, I do one sample that you can take a look.

Here is the CaruselPage:

<CarouselPage
x:Class="CaruselApp.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<CarouselPage.ItemTemplate>
    <DataTemplate>
        <ContentPage>
            <StackLayout>

                <Label Margin="10" Text="{Binding title}" />
                <CollectionView ItemsSource="{Binding collections}">
                    <CollectionView.ItemsLayout>
                        <GridItemsLayout Orientation="Vertical" Span="1" />
                    </CollectionView.ItemsLayout>
                    <CollectionView.ItemTemplate>
                        <DataTemplate>
                            <Frame BorderColor="Black">
                                <StackLayout>

                                    <Label Text="{Binding Name}" />
                                    <Label Text="{Binding Age}" />
                                </StackLayout>
                            </Frame>

                        </DataTemplate>
                    </CollectionView.ItemTemplate>
                </CollectionView>
            </StackLayout>
        </ContentPage>
    </DataTemplate>
</CarouselPage.ItemTemplate>

The Model in CollectionView:

public class CollectionModel
{
    public string Name { get; set; }
    public int Age { get; set; }
}

The Model in CarouselPage:

 public class CaruselModel
{
    public ObservableCollection<CollectionModel> collections { get; set; }

    public string title { get; set; }

    public static ObservableCollection<CaruselModel> carusels { get; set; }

     static CaruselModel()
    {
        carusels = new ObservableCollection<CaruselModel>()
        {
            new CaruselModel(){title="title 1", collections=new ObservableCollection<CollectionModel>(){ new CollectionModel() { Name="Cherry",Age=12},new CollectionModel() { Name="barry",Age=23} } },
             new CaruselModel(){title="title 2", collections=new ObservableCollection<CollectionModel>(){ new CollectionModel() { Name="Annine",Age=18},new CollectionModel() { Name="Wendy",Age=25} } },
              new CaruselModel(){title="title 3", collections=new ObservableCollection<CollectionModel>(){ new CollectionModel() { Name="Mattew",Age=12},new CollectionModel() { Name="Leo",Age=23} } },
               new CaruselModel(){title="title 4", collections=new ObservableCollection<CollectionModel>(){ new CollectionModel() { Name="Jessie",Age=12},new CollectionModel() { Name="Junior",Age=23} } },
                new CaruselModel(){title="title 5", collections=new ObservableCollection<CollectionModel>(){ new CollectionModel() { Name="Jack",Age=12},new CollectionModel() { Name="Land",Age=23} } }

        };

    }
}

Please don't forget to add the following code in Android Mainactivity or ios AppDelegate, because you use CollectionView.

 Forms.SetFlags("CollectionView_Experimental");

Here is the sample at Github, you can download to test.

https://github.com/CherryBu/CarouselApp

her is the screenshot:

enter image description here



Answered By - Cherry Bu - MSFT
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how can I create a rectangular as big as the screen in Xamarin Forms?

 September 12, 2022     cross-platform, xamarin, xaml     No comments   

Issue

I'm trying to make a rectangular in XAML Xamarin Forms, how can I set Height and Width to be as big as the phone screen ? HeightRequest and widthRequest seems don't work I want to make a thick transparent border around the camera frame so I want to make rectangular as big as the screen, how can i set these to fit all sizes of screens ?

<StackLayout>
    <Grid VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
        <xct:CameraView x:Name="cameraView"  CameraOptions="Back" CaptureMode="Photo" OnAvailable="CameraView_OnAvailable">
            <xct:CameraView.Behaviors >
                <xct:EventToCommandBehavior Command="{Binding PhotoCapturedCommand}" EventName="MediaCaptured" />
            </xct:CameraView.Behaviors>
        </xct:CameraView>
        <Rectangle  HeightRequest="1*" Fill="Transparent" Stroke="Blue" Opacity="0.7" StrokeThickness="150"/>

    </Grid>

</StackLayout>

Solution

Absolute Layout has 2 great advantages:

  1. As it name implies, the position/size of the element is absolute

  2. You can "Stack" elements making layers

For this example, the CameraView will occupy 100% of the screen, and the "Mask" will be 50%. These value are going to be proportional of the screen size (this is only an example). Make sure to check for every screen that the image do not distort

<AbsoluteLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
    <xct:CameraView x:Name="cameraView"  CameraOptions="Back" CaptureMode="Photo" OnAvailable="CameraView_OnAvailable" AbsoluteLayout.LayoutBounds="0.5,0.5,1,1" AbsoluteLayout.LayoutFlags="All">
        <xct:CameraView.Behaviors >
            <xct:EventToCommandBehavior Command="{Binding PhotoCapturedCommand}" EventName="MediaCaptured" />
        </xct:CameraView.Behaviors>
    </xct:CameraView>
    <Frame BackgroundColor="Transparent" BorderColor="White" AbsoluteLayout.LayoutBounds="0.5,0.5,0.5,0.5" AbsoluteLayout.LayoutFlags="All"/>
</AbsoluteLayout>

You can put this code inside any other component if you want



Answered By - Juan Sturla
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How change color of three btn at toolbar crossplatform

 September 12, 2022     c#, cross-platform, xamarin.forms, xaml     No comments   

Issue

I could not understand why the button with dots is not displayed. But clicking in this area opens drop-down menus.

enter image description here

The dots on the button are white and they just blend in with the background. I found a solution for android, but how do I go about making a cross platform solution to the problem?

enter image description here

<ContentPage.ToolbarItems>
    <ToolbarItem 
        Order="Secondary"
        
        Text="Item 0"
        Priority="0"/>
    <ToolbarItem 
        Order="Secondary"
        Text="Item 1"
        Priority="1"/>
    <ToolbarItem 
        Order="Secondary"
        Text="Item 2"
        Priority="2"/>
</ContentPage.ToolbarItems>

Solution

When the Order property is set to Secondary, behavior varies across platforms. On UWP and Android, the Secondary items menu appears as three dots that can be tapped or clicked to reveal items in a vertical list. On iOS, the Secondary items menu appears below the navigation bar as a horizontal list.

A easy is to change the background color of the toolbar.

App.xaml.cs:

 var navPage = new NavigationPage(new Page2());
        this.MainPage = navPage;

        navPage.BarBackgroundColor = Color.Blue;

enter image description here

Update:

Android:

Change the color of 3 dots in style:

  <style name="MainTheme" parent="MainTheme.Base">  
<item name="android:textColorSecondary">#54FF9F</item> 
</style>

Use the androidx.appcompat.widget.Toolbar in the Toolbar.xml:

  <?xml version="1.0" encoding="utf-8"?>
 <androidx.appcompat.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" 
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:theme="@style/MainTheme"
android:popupTheme="@style/MainTheme.Base" 
 />

enter image description here

iOS:

Like what i said in previouss reply, the Secondary items menu on ios appears below the navigation bar as a horizontal list.

enter image description here

You could use IOSToolbarExtensions instead.

NuGet: https://www.nuget.org/packages/IOSToolbarExtensions/

Install it and add the code below into AssemblyInfo.cs:

[assembly: ExportRenderer(typeof(ContentPage), typeof(IOSToolbarExtensions.iOS.Renderers.IOSToolbarExtensionsContentPageRenderer), Priority = short.MaxValue)]

enter image description here



Answered By - Wendy Zang - MSFT
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, May 6, 2022

[FIXED] How to set up the image source path properly in XAML

 May 06, 2022     image, wpf, xaml     No comments   

Issue

i'm trying to put a close button image on my newly created tabs for my app, but i just can't seem to get the right path. This is how i've tried inputting it (code is from MainWindow.xaml):

<TabControl Margin="10,26,10,10" ItemsSource="{Binding FileTabs}">
            <TabControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding FileTabName}" />
                        <Button Name="closeTabBtn">
                            <Image Width="20" Height="20" Source="/Images/button-close.jpg" />
                        </Button>
                    </StackPanel>
                </DataTemplate>
            </TabControl.ItemTemplate>

This is my project structure:

enter image description here

What is the correct path for the image source property since i'm kind of new at this ?


Solution

You should set the Build Action of the image file to Resource in Visual Studio and try with a pack URI if your relative path still doesn't work:

Source="pack://application:,,,/Images/button-close.png"


Answered By - mm8
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing