Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 89864 articles
Browse latest View live

Label Text binding does not work when I also use IsVisible binding

$
0
0

Hi,

I have a label with two bindings: Text binding and also IsVisible binding.

I have a special situation where I cannot see the content of my label. I know the label control is there because the space is reserved in the UI but no value is displayed. When I start the simulator in debug, I see the problem. Even if I go around the app, the problem is always there. But if I update the Label control and save (hotswap), after the refresh of the App, the problem is fixed!?!

Here is my model. Each ListViewItem has a small arrow at the bottom and when I click on it, I want to hide the label and show another section. When I click again on the arrow, hide the section and show the label. Just toggle between these two.

public class EvaluationContextMemberCell : INotifyPropertyChanged, IProfileUniform
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public EvaluationContextMemberDto EvaluationContextMember { get; set; }

    ...    

        #region Position
        public bool HasPosition { get { return EvaluationContextMember.Profile.Position.IsNotEmpty(); } }

        public bool ShowPosition { get { return HasPosition && !ShowProperties; } }
        #endregion

    .. 

        #region Properties
        public List<ProfilePropertyDto> Properties
        {
            get
            {
                List<ProfilePropertyDto> properties = new List<ProfilePropertyDto>(EvaluationContextMember.Profile.Properties);

                if (EvaluationContextMember.Profile.Subject.Gender.HasValue)
                {
                    ProfilePropertyDto dto = new ProfilePropertyDto
                    {
                        Name = AppResources.Gender,
                        Value = EvaluationContextMember.Profile.Subject.Gender == 2 ? AppResources.GenderFemale : AppResources.GenderMale
                    };
                    properties.Insert(0, dto);
                }

                if (EvaluationContextMember.Profile.Subject.Date.HasValue)
                {
                    DateTime birthdate = EvaluationContextMember.Profile.Subject.Date.Value;
                    DateTime referenceDate = DateTime.Now;

                    int age = referenceDate.Year - birthdate.Year;
                    if (birthdate > referenceDate.AddYears(-age))
                    {
                        age--;
                    }

                    ProfilePropertyDto dto = new ProfilePropertyDto
                    {
                        Name = AppResources.Age,
                        Value = age
                    };
                    properties.Insert(0, dto);
                }

                if (EvaluationContextMember.Profile.Position.IsNotEmpty())
                {
                    ProfilePropertyDto dto = new ProfilePropertyDto
                    {
                        Name = AppResources.Position,
                        Value = EvaluationContextMember.Profile.Position
                    };
                    properties.Insert(0, dto);
                }

                return properties;
            }
        }

        public bool HasProperties { get { return Properties.IsNotEmpty(); } }

        public bool ShowProperties { get; set; }
        #endregion

        public ICommand ExpandCollapseClickCommand { get; set; }

        public Action<EvaluationContextMemberCell> IsShowPropertiesChangedAction { get; set; }

        public EvaluationContextMemberCell()
        {
            ExpandCollapseClickCommand = new Command((obj) => {
                ShowProperties = !ShowProperties;
                OnPropertyChanged("ShowProperties");
                OnPropertyChanged("ShowPosition");
                IsShowPropertiesChangedAction.Invoke(this);
            });
        }

        protected void OnPropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }

Settings Plugin not persisting between deployments

$
0
0

Hey guys -

I am using the @JamesMontemagno Settings Plugin. Data saves fine, but I lose the data when I deploy from Visual Studio. I do have the "Preserve application data cache on device between deploys" in Studio selected (although I haven't been able to tell if the settings plugin is supposed to use this or not).

So two questions. First, is this the expected behavior? If so, is there a way to make it so that it doesn't lose this data? Since my app uses two factor authentication, I am having to re-authenticate my device each time that I re-deploy - which is quite often when debugging on my phone.

Second - I am concerned that this behavior would also happen when I deploy my app to the app store. I push out updates a couple of times a month and I don't want my user's to have to re-authenticate their devices that often.

I am running Visual Studio 2019 in debug mode and deploying to a Samsung S20+. I have not tried this plugin on iOS yet so I am not sure if this is happening there as well.

Thanks!

Saving Picker SelectedItem to a table Binding

$
0
0

Hi! I am trying to save the selected item from the picker to a string which i can save in my sqlite table. I have used the MVVM and I dont know how to go any further. Here is my view model:

` public List Ingredients { get; set; }
public OilPickerViewModel()
{
Ingredients = GetIngredients().OrderBy(t => t.Value).ToList();
}

    public List<Ingredient> GetIngredients()
    {
        var ingredients = new List<Ingredient>()
        {
            new Ingredient(){Key = 1, Value = "Lavanda"},
            new Ingredient(){Key = 2, Value = "Peppermint"}
          };
        return ingredients;
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
    private Ingredient _selectedIngredient1 { get; set; }
    public Ingredient SelectedIngredient1
    {
        get { return _selectedIngredient1; }
        set
        {
            if(_selectedIngredient1 != value)
            {
                _selectedIngredient1 = value;
                MyIngredient1 = _selectedIngredient1.Value;
            }
        }
    }
    private string myIngredient1 { get; set; }
    public string MyIngredient1
    {
        get { return myIngredient1; }
        set
        {
            if( myIngredient1 != value)
            {
                myIngredient1 = value;
                OnPropertyChanged();
            }
        }
    }`

Here it is what I have written in my view:
<Picker x:Name="ulei1Picker" Title="Alege primul ingredient" ItemsSource="{Binding Ingredients}" ItemDisplayBinding="{Binding Value}" SelectedItem="{Binding SelectedIngredient1}"/> <Button Text="Salveaza" x:Name="saveButton" Clicked="SaveButton_Clicked"/>

and my code-behind:

void SaveButton_Clicked(object sender, EventArgs e) { if ( ulei1Picker.SelectedItem == null ) { DisplayAlert("...");} else { Blend blend = new Blend() { Ulei1 = ulei1Picker.SelectedItem?.ToString() }}
I need the selected value from the picker to be saved to the Ulei1 string from the table but i just cant. How do I make this work?>!

Navigation back button accessibility name

$
0
0

If you have enabled the navigation page, with the back button (the "<" icon) and the title, when the screen reader focus is on the back button it read "unlabeled button". Is there a way to change is Accessibility name to a proper "back button" or whatever else? Either in Android and iOS

How to change the name of app(In the screen, under the icon)

$
0
0

Hi guys,

I am building an app in Xamarin.Forms. I want to change the name of app, both iOS and Android. I tried to change the information in mainactivity.cs and Androidmanifest. However it is not working. I also don't know how to do it in iOS.

Would you please to help me?

Thank you very much.

About data base

$
0
0

Tengo una app desarrollada en xamarin forms con visual studio 2017, la app tiene una base de datos la cual genero una vez que ejecuto la aplicacion, ahora bien, lo que nesecito es saber como puedo obtener ese archivo(base de datos) porque no la veo por ningun lado....asi creo mi base de datos con sus correspondientes tablas

if (database == null)
{
database = new Database(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Infractores.db3"));
}
return database;

El emulador que utilizo es el nox player 6.6

Y como puedo hacer para que la app se me conecte a un servidor externo donde estara esa base de datos y poder consumir datos de ella
saludos y gracias por addelantado

################ English

I have an app developed in xamarin forms with visual studio 2017, the app has a database which I generate once I run the application, now what I need is to know how I can get that file (database) because I don't I see nowhere ... so I create my database with its corresponding tables

if (database == null)
{
database = new Database (Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.LocalApplicationData), "Violators.db3"));
}
return database;

The emulator I use is the nox player 6.6

And how can I make the app connect to an external server where that database will be and be able to consume data from it
greetings and thanks in advance

iOS "Files" app, Android ExternalStorageDirectory and saving files

$
0
0

Hello,

Trying to rephrase a question I've asked before.

I'd like to save a generated .pdf file into a common folder on a device so that a user can find those files from say email app for an attachment or just view the file external to my app.

On my iOS device, I can open Files app and browser to various folders. I noticed some apps have their own folders under "On my phone" and I can manually create a folder there too.

I'd like my app to create it's own public folder on the device and save pdf files into that. The user can then view those files by simply navigating to that folder without needing to use my app.

Found these two links - files in iOS
and this BlogPost for Android

Can anyone else advise?
As there a plugin or sample code that'll help?

I'm expecting to write a dependency service for this on each platform.

Thanks

Using custom font in Xamarin adds extra spacing below and above the text

$
0
0

Hello

I would like to use custom ( imported ttf ) font in Xamarin. I use Xamarin.Forms 4.4, I put ttf into Assets folder of my android project.
But when I display some text with this font, text is displayed with extra spacing above and below text ( red bordered areas on pic)

The VerticalTextAlignment works fine, but I don't know what are these spaces ( I guess these spaces are gaps between top and ascent values of font , and bottom and descent values of font) and how can I remove them? I tried set font metrics with fontforge (on Element -> Font info->OS/2->Metrics pane) but no effect.

I tried other ttf font, that font has extra spacing too, but size of spacing above and below text was different.

Xaml for upper Sample text:
<Label Text="Sample text" FontFamily="font.ttf#font name" FontSize="26" LineHeight="12" FontAttributes="Bold" VerticalOptions="End" VerticalTextAlignment="Start" BackgroundColor="Aqua" Padding="0" Margin="0" HeightRequest="100"/>

Xaml for other Sample text:
<Label Text="Sample text" FontFamily="font.ttf#font name" FontSize="26" LineHeight="12" FontAttributes="Bold" VerticalOptions="End" VerticalTextAlignment="Start" BackgroundColor="Aqua" Padding="0" Margin="0"/>

Thanks for your help


PancakeView performance

$
0
0

What experiences have you had with the pancakeview nuget? Does this package give good visual performance?

How to intercept Navigation Bar Back Button Clicked in Xamarin Forms?

$
0
0

I have a xamarin forms page where the user can update some data in a form. I need to intercept the Navigation Bar Back Button Clicked to warn the user if some data have not been saved.How to do it?

I'm able to intercept the hardware Bar Back Button Clicked in Android using the Android.MainActivity.OnBackPressed(), but that event is raised only on hardware Bar Back Button Clicked, not on Navigation Bar Back Button Clicked.

I tried also to override Xamarin.Forms.NavigationPageOnBackButtonPressed() but it not works. Why? Any one have already solved that issue?

I also tried by overriding OnDisappear, there are two problems:

The page has already visually disappeared so the "Are you sure?" dialog appears over the previous page.
Cannot cancel the back action.
So,is it possible to intercept the navigation bar back button press?

Thanks for any help on this.

Problems using ListView with SwipeView overlapping rows

$
0
0

Hi

I am trying to slide the ListView item to the left to access the Delete button.
When I slide the second line after the first, the first line does not return to the original position and
when I slide the other lines to the left, ONLY the last line is shown correctly, in the lines above the lines are superimposed.

See image

See xaml code

                   <ListView.ItemTemplate >
                        <DataTemplate >
                            <ViewCell >
                                    <SwipeView>
                                        <SwipeView.RightItems>
                                            <SwipeItems Mode="Reveal" >
                                                <SwipeItem Text="Excluir"          
                                                           CommandParameter="{Binding Source={x:Reference Item}, Path=BindingContext}"
                                                           BackgroundColor="Red" 
                                                           IconImageSource="delete.png"
                                                           Invoked ="IB_Invoked">
                                                </SwipeItem>
                                            </SwipeItems>
                                        </SwipeView.RightItems>

                                        <!-- conteudo do swipe view-->
                                        <Frame CornerRadius="20" Margin="1,1,1,1" HasShadow="True"  BorderColor="DarkBlue">
                                            <Grid x:Name="Item">
                                                <Grid.RowDefinitions>
                                                    <RowDefinition Height="40"/>
                                                </Grid.RowDefinitions>
                                                <Grid.ColumnDefinitions>
                                                    <ColumnDefinition Width="50"/>
                                                    <ColumnDefinition Width="*"/>
                                                    <ColumnDefinition Width="60"/>
                                                    <ColumnDefinition Width="90"/>
                                                </Grid.ColumnDefinitions>

                                                <Grid BackgroundColor="Blue">
                                                    <Label Grid.Row="0" Grid.Column="0" Text="{Binding QTY}"  Font="20" VerticalOptions="Center" HorizontalTextAlignment="Center" TextColor="White" />
                                                </Grid>
                                                <StackLayout Grid.Row="0" Grid.Column="1" Orientation="Horizontal">
                                                    <Label Text="{Binding DESCRIPTION}" VerticalTextAlignment="Center" Font="14" TextColor="Black" />
                                                </StackLayout>
                                                <StackLayout Grid.Row="0" Grid.Column="2" Orientation="Horizontal" HorizontalOptions="End">
                                                    <Label Text="{Binding TOTAL, StringFormat='{0:N2}'}" VerticalTextAlignment="Center" Font="14" TextColor="Black" />
                                                </StackLayout>
                                            </Grid>
                                        </Frame>
                                    </SwipeView>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>

Expander error

$
0
0

Hi,

i'm getting a extrange error with new Expander control and an error of System.Reflection.TargetInvocationException, because in another test project it's working, at least a basic test.
I've a content page, with a Pancake View, with a Collection View, and i haven't any Expander control.
And here comes strange error, if i only add Device.SetFlags(new string[] { "Expander_Experimental" }); to App.xml.cs, and not add a Expander control in View, when i navigate to page (i'm in MVVM model), i get a System.Reflection.TargetInvocationException.

This is the output result.

05-03 12:02:50.978 D/Mono ( 3498): Requesting loading reference 13 (of 20) of /storage/emulated/0/Android/data/com.test.Test.Mobile/files/.override/Test.Mobile.dll
05-03 12:02:50.978 D/Mono ( 3498): Loading reference 13 of /storage/emulated/0/Android/data/com.test.Test.Mobile/files/.override/Test.Mobile.dll asmctx DEFAULT, looking for Xamarin.Forms.PancakeView, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null
05-03 12:02:50.978 D/Mono ( 3498): Assembly Ref addref Test.Mobile[0xaac20e60] -> Xamarin.Forms.PancakeView[0xab27b9e0]: 2
Loaded assembly: Anonymously Hosted DynamicMethods Assembly [External]
System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'

Another error, if i set a breakpoint into source ViewModel (MainViewModel), where i've a command to navigate to this page (ExpanderViewModel->ExpanderPage), i'm getting too System.Reflection.TargetInvocationException , but in System.Core. And brekpoint doesn't work,

async Task ViewTestExpander() {
        if (Condition)  //BreakPoint here, and doesn't work
                await NavigationService.NavigateToAsync(typeof(ViewModels.Main.ExpanderViewModel)).ConfigureAwait(false);
            }

if i remove this line Device.SetFlags(new string[] { "Expander_Experimental" }); from App.xml.cs, all works fine.

Any idea, or suggestion?
Many thanks guys

Issue: InstallFailedException

$
0
0

I am currently having an issue with running my Xamarin.Forms app on my mobile device whether it be emulated or my physical test device.
I am on Visual Studio 2019 and it is a new app project and I have had it running before but usually after the first run it does not work again after that if it did.
The error code is as follows:

ADB0010: Mono.AndroidTools.InstallFailedException: Failure [INSTALL_FAILED_INVALID_APK: Package couldn't be installed in /data/app/com.companyname.appname-w4jR_g7Ki-eDsfg24hSJUA==: Package /data/app/com.companyname.appname-w4jR_g7Ki-eDsfg24hSJUA==/base.apk code is missing]
   at Mono.AndroidTools.Internal.AdbOutputParsing.CheckInstallSuccess(String output, String packageName) in E:\A\_work\254\s\External\androidtools\Mono.AndroidTools\Internal\AdbOutputParsing.cs:line 341
   at Mono.AndroidTools.AndroidDevice.<>c__DisplayClass95_0.<InstallPackage>b__0(Task`1 t) in E:\A\_work\254\s\External\androidtools\Mono.AndroidTools\AndroidDevice.cs:line 753
   at System.Threading.Tasks.ContinuationTaskFromResultTask`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at AndroidDeviceExtensions.<PushAndInstallPackage>d__11.MoveNext() in E:\A\_work\254\s\External\androidtools\Xamarin.AndroidTools\Devices\AndroidDeviceExtensions.cs:line 187
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at AndroidDeviceExtensions.<PushAndInstallPackage>d__11.MoveNext() in E:\A\_work\254\s\External\androidtools\Xamarin.AndroidTools\Devices\AndroidDeviceExtensions.cs:line 203
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Xamarin.AndroidTools.AndroidDeploySession.<InstallPackage>d__112.MoveNext() in E:\A\_work\254\s\External\androidtools\Xamarin.AndroidTools\Sessions\AndroidDeploySession.cs:line 414
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Xamarin.AndroidTools.AndroidDeploySession.<RunAsync>d__106.MoveNext() in E:\A\_work\254\s\External\androidtools\Xamarin.AndroidTools\Sessions\AndroidDeploySession.cs:line 217
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Xamarin.AndroidTools.AndroidDeploySession.<RunLoggedAsync>d__104.MoveNext() in E:\A\_work\254\s\External\androidtools\Xamarin.AndroidTools\Sessions\AndroidDeploySession.cs:line 119

I have tried many things including:
Repairing the SDK
Uninstalling Visual Studio, Android Studio, Android SDK and then re-installing them

Need to refresh calling ContentPage when called ContentPage is finished

$
0
0

OK, so this is an MVVM project.

I have a ContentPage (StudentListPage with StudentListViewModel) that presents a list of passing students. When a student is tapped (his name is Charlie) we go to another ContentPage, called StudentDetailPage with StudentDetailViewModel. We change the Charlie's status from passing to failing, save the record, then hit the android back button.

How does the StudentListViewModel get informed that StudentDetailViewModel updated Charlie's status, and that we should now refresh the list?

I could probably do this with some sort of kludgey code-behind madness, but I want to avoid gyrations. I'm looking for something quick, clean, correct and understandable. The best thing I've come up with so far, is to have the Detail VM send to a MessageCenter, and have the List VM subscribe to it and refresh when it detects an "i-just-saved" message from the Detail VM.

How to use Done in picker

$
0
0

How do i use the Done button in a picker .

Am loading some text from a database using a picker , after selecting an item it is going to do download the text.

But i want to use the "Done" button and not SelectedIndexChanged="picker_SelectedIndexChanged"


How to make the app open on the same place you left it last time?

$
0
0

Hi everyone, first question ever.
I am very new on Xamarin, making my first project, so I would very much appreciate detailed answers.

My app consists basically on a book. I am using CarouselPage, in which every chapter of the book is one of the carousel pages.

My question is how do I make sure that every time someone runs the app, it "saves the progress" and opens where you left it last time.

Thanks everyone!

How to relocate items in a RelativeLayout?

$
0
0

Imagine a simple RelativeLayout that consists of a Button, a Label and a TextBox.
The Button is positioned relative to the parent.
The Label is positioned relative to the Button.
The TextBox is positioned relative to the Label so they are all in a nice column.

Under certain conditions the Label is not visible. That is because the Label displays messages and sometimes there are no messages to display. When that happens, there is a blank space between the Button and the TextBox. When the Label is not Visible, I would like to move the TextBox up a bit to fill in the blank space.

How can I do that using a RelativeLayout?

Of course I could do it all with a StackLayout and have done it several times. But there is a long story that means that I have to use a RelativeLayout this time (or an AbsoluteLayout).

From my research, it seems that if I define the whole page in code, when things change I can remove all the children and re-add them. I would prefer not to do that as there are a lot of items on the page (more than the three in my example). So I am looking for an alternative way to accomplish this while hopefully keeping my XAML.

Thanks for reading this and I look forward to your answers.

how to invoke a hub methods using signalr private chat app

$
0
0

THIS IS MY HUB AND I'M USING Aspnet.signalr NOT AspnetCore.signalr

public class MobileHub : Hub
{
public static Dictionary<string, string> LstAllConnections = new Dictionary<string, string>();

    public override Task OnConnected()
    {
        LstAllConnections.Add(Context.ConnectionId, "");
        Clients.All.BroadcastConnections(LstAllConnections);
        return base.OnConnected();
    }

    public override Task OnDisconnected(bool stopCalled)
    {
        LstAllConnections.Remove(Context.ConnectionId);
        Clients.All.BroadcastConnections(LstAllConnections);
        return base.OnDisconnected(stopCalled);
    }

    public void SetConnectionName(string connectionname)
    {
        LstAllConnections[Context.ConnectionId] = connectionname;
        Clients.All.BroadcastConnections(LstAllConnections);
    }

    public void Send(string partnerId, string message)
    {
        User from = new User { Id = Context.ConnectionId, Name = LstAllConnections[Context.ConnectionId] };
        Clients.Clients(new List<string> { Context.ConnectionId, partnerId }).BroadcastMessage(from, message);
    }


    public class User
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

Change ShellContent programatically

$
0
0

Hi there I want to have 2 routes depending on a preference setting, how can I change the XAML line ContentTemplate="{DataTemplate views:CatsPage}" from the code behind?

     <ShellContent Title="Cats"
                      Icon="cat.png"
                      ContentTemplate="{DataTemplate views:CatsPage}" />
        <ShellContent Title="Dogs"
                      Icon="dog.png"
                      ContentTemplate="{DataTemplate views:DogsPage}" />

Duration of Recorded Video

$
0
0
I have recorded a video using Xam.Plugin.Media. But I also want to retrieve the total duration of the recorded video. How can I achieve this? Please help
Viewing all 89864 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>