Is there a way to deselect a listview item in a viewmodel without having to do it in the xaml code behind?
MVVM viewmodel deselect listview item
Current device sim phone number
Hi,
I am trying to get the current device sim phone number in platform neutral way, I have tried: Xam.Plugin.Contacts & DeviceInfoPlugin plugins but could not find relevant api for it.
Any help would be greatly appreciated.
-Thanks
How to get button click parameters to ICommand in model view?
In button click even it passes two parameters to the code behind (object sender, EventArgs e).
private void CheckBox_Event(object sender, EventArgs e)
{}
But if I use Command instead of click event how to pass that object sender parameter to that command in model view?
ICommand MyCommand = new Command(() =>
{
});
Because I am using this to handle a check box event inside a listview. I wanna get that clicked checkbox.
Picker Unfocused event on UWP
Hi,
I have a problem with Xamarin Forms Picker.
I am using unfocused event to open a popup when user selects an item. On Android works well, when picker is closed event is fired but, in UWP, the event is fired when combobox popup is opened preventing change selection.
Anyone know how I can put an event when picker is closed for Android and UWP? I can't use SelectedIndexChanged because if the user choose the same item as the item is currently being selected then the selection is not changed and therefore this event will not be triggered.
Thanks in advance!
How to video call via Twilio from Xamarin Forms
Hello everyone.
I want to use Twilio in a Portable Xamarin Forms project.
I have seen some approaches to the bindings here: github.com dkornev TwilioXamarinBindings
I can use that app as is, but it is not using Xamarin Forms.
In an attempt to make a Forms version I assumed that I could use the Dependency Service and an Interface to call the neccessary methods to connect to a room etc. However, how can I set the video on a Xamarin Forms Page component?
Using ResourceDictionary from another assembly compile error
I'm trying to use ResourceDictionary from another assembly in App.xaml like this:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/UIServiceLib;component/ResourceDictionaries/CommonDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
and I'm getting compile error:
Invalid URI value: The specified port is invalid.
Rebuilding/cleaning solution didn't help. How can I solve this issue?
Css or Xaml Styling
Since I've started with Xamarin, I've always been using xaml for styling. I was wondering if I should give it a try to css styling. It's true that css looks much cleaner and readable, etc. But I have some questions before going for it:
- How to specify custom fonts in css for xamarin forms? In the samples I couldn't find custom fonts.
- How to set different values for each platform, just like OnPlatform in xaml?
- How to specify a color palette and use it in my css styles?
I know those questions look basic, but I couldn't find good examples.
Would you rather css or xaml for styling?
How to MessagingCenter.Subscribe to same message from multiple senders
I want to subscribe to a message that can be sent from multiple ViewModels. Is there a more elegant solution than subscribing individually for each ViewModel, like I do below?
MessagingCenter.Subscribe<Page1Model, bool>(this, "SomeMessage", MyMethod);
MessagingCenter.Subscribe<Page2Model, bool>(this, "SomeMessage", MyMethod);
Button Command not triggering inside view model
I have a Button in my view and I have a View model bind to that view. My problem is, command not triggering inside the view model.
My view Model.....
**iPayBtnCommand ** is the command ....
namespace CustApp.CusApp.Dushan.ViewModel
{
public class LifeDemandVM : INotifyPropertyChanged
{
public LifeDemandVM() {
paymentEnabled = false;
advancedPayment = null;
MyCommand = new Command((object sender) =>
{
selectedList = new ObservableCollection<LifeDemandData>();
selectedList.Clear();
double summ = 0;
if (((CheckBox)sender).IsChecked)
{
}
else
{
}
foreach (LifeDemandData ss in selectedList)
{
summ = Convert.ToDouble(ss.PREMIUM) + Convert.ToDouble(ss.LATEFEE) + summ;
}
if (summ > 0)
{
canPay = true;
sumValue = summ.ToString("N", CultureInfo.InvariantCulture);
demandSum = summ;
}
else
{
canPay = false;
sumValue = "0.00";
}
if (selectedList.Count > 1)
{
txtDemand = "Demands Rs. ";
}
else
{
txtDemand = "Demand Rs. ";
}
});
}
public async Task getLifeDemands(string polNo)
{
IsBusy = true;
string demandRequest = await _apiServices.getLifeDemandList(polNo);
var varModel = JsonConvert.DeserializeObject<List<LifeDemandData>>(demandRequest);
LifeDemandList = new ObservableCollection<LifeDemandData>();
LifeDemandList.Clear();
foreach (LifeDemandData ss in varModel)
{
LifeDemandData lifeData = new LifeDemandData();
lifeData.DEMAND = ss.DEMAND;
lifeData.LATEFEE = ss.LATEFEE;
lifeData.PREMIUM = ss.PREMIUM;
lifeData.ROWCHECK = ss.ROWCHECK;
lifeData.CheckedCommand = MyCommand;
LifeDemandList.Add(lifeData);
}
LifeDemandListSource = LifeDemandList;
IsBusy = false;
}
public void setSwitchToggle(bool value)
{
if (value)
{
paymentEnabled = true;
}
else
{
paymentEnabled = false;
advancedPayment = null;
}
}
public ICommand iPayBtnCommand
{
get
{
return new Command(async () =>
{
await Application.Current.MainPage.Navigation.PushAsync(new ContactUs());
});
}
}
private async void PromptCommand(string action)
{
double totalSum = 0;
if (advancedPayment == null || advancedPayment.Equals("") || advancedPayment.Equals("."))
{
totalSum = demandSum;
}
else
{
totalSum = demandSum + Double.Parse(advancedPayment);
}
if (action.Equals("Frimi"))
{
await Application.Current.MainPage.Navigation.PushAsync(new PayViaFrimi_Life(totalSum));
}
else if (action.Equals("mCash"))
{
await Application.Current.MainPage.Navigation.PushAsync(new PayViaMcash_Life(totalSum));
}
else
{
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
View part.......
<StackLayout Margin="0,10,0,5" HorizontalOptions="CenterAndExpand">
<Button Command="iPayBtnCommand" Style="{StaticResource homeBtn}" Text="Pay now"/>
</StackLayout>
CS class....
namespace CustApp.CusApp.Dushan.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SelectLifeDemands : ContentPage
{
private LifeDemandVM vm;
public SelectLifeDemands()
{
InitializeComponent();
}
public SelectLifeDemands(string polNo)
{
InitializeComponent();
Title = "Life Demand";
BindingContext = new LifeDemandVM();
vm = BindingContext as LifeDemandVM;
Task.Run(async () =>
{
await vm.getLifeDemands(polNo);
});
}
}
}
Xamarin Forms WebView and Gesture Recogniser issues with Android
Hello all,
I have developed an app with WebView to display local HTML content. I have also added Swipe GestureRecognizers to the WebView to update the source binding content to load new HTML files when user swipes right or left. The Xaml code for this is shown below:
<WebView
x:Name="HtmlView"
Grid.Row="1"
Source="{Binding HTMLFile}"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
GoBackRequested="Handle_GoBackRequested"
GoForwardRequested="Handle_GoForwardRequested"
>
<WebView.GestureRecognizers>
<SwipeGestureRecognizer Direction="Left" Swiped="Handle_SwipedLeft"/>
<SwipeGestureRecognizer Direction="Right" Swiped="Handle_SwipedRight"/>
</WebView.GestureRecognizers>
</WebView>
and the gesture recognisers:
void Handle_GoForwardRequested(object sender, System.EventArgs e)
{
flashCard.HTMLFile = getHTMLFileFromDevice("FlashCard2.html");
HtmlView.Reload();
}
void Handle_GoBackRequested(object sender, System.EventArgs e)
{
flashCard.HTMLFile = getHTMLFileFromDevice("FlashCard3.html");
HtmlView.Reload();
}
This works completely fine with iOS, but when I launch it on android (emulator) the gesture handlers dont get triggered at all. Is there an issue with android and gesture recognisers?
Thanks
can you run xamarin ui Test (iOS) on visual studio 2019
Hi wondering if you can run a xamarin ui Test (iOS) on visual studio 2019 using a mac mini connectivity launching a simulator?
I keep reading contradictory statements about it.
Could somebody clarify if you can run xamarin ui tests (iOS) on visual studio 2019 connecting to a mac mini?
many thanks
Should I prefer using x:Binding over Binding?
Why do both of them exist? I believe the first one is compiled binding? I turned on XAML compilation for every XAML file, but should I also start using x:Binding
everywhere I use Binding
?
And there is no x:Bind
, correct? Is x:Binding
the same as x:Bind
?
blur background effect for frame
Hello,
I need an effect to blur the background for frame or stacklayout. Is there a native render that can do this for android and ios?
Thx
Xamarin.Forms android app won't build anymore after adding "Xamarin.Firebase.Messaging" to it
After adding the nuget package "Xamarin.Firebase.Messaging" to a xamarin.forms application in VS2019 it wont build anymore.
You can replicate this issue by creating a new xamarin.forms application and adding "Xamarin.Firebase.Messaging" to it.
The build error it throws is: "Did not find reference matching RestoreAssemblyResources AssemblyName metadata 'Xamarin.Firebase.Messaging'"
This essentially happens when adding any push notification package since they all use Firebase.Messaging.
Any way to fix this and get push notifications to work in xamarin.forms for android?
Displaying badge in Xamarin Forms Android Application
Hi Guys,
I have a requirement to set custom value to application badge icon.
I am using Xamarin.Badge.Plugin , Plugin.Badge. But I was not able to set custom values to badge.
I have two android devices Samsung galaxy s8, lava iris.
Lava ( Android 6.0 )is working fine , i can set any values to badge icon.
Samsung S8 ( Android 9.0 ), not displaying any custom values.( had enabled notification in app settings )
i did tried with all the plugins and renderers available now, still no luck.
any one faced this issue before ?
any solutions ?
You MUST call Xamarin.Forms.Init(); prior to using it
In my app.xaml.cs I create a new page.
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new WrapLayoutPage());
}
This page calls a static class, which uses the DependencyService to perform some tasks. This throws me a TypeInitializationException with the InnerException "You MUST call Xamarin.Forms.Init(); prior to using it". Normally it would be pretty clear, but since I call this in my MainActivity in the android project, I really don't know what I'm supposed to do.
[Activity(Label = "FrameworkForms", Icon = "@drawable/icon", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, Theme = "@android:style/Theme.Material.Light")]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Xamarin.Forms.Forms.Init(this, bundle);
App.ScreenWidth = (double)(Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density);
LoadApplication(new App());
}
}
Any Solution for PDF reader
hi
I am unable to find a solution for for PDF reader in Xamarin forms.
The solution provided on xamarin website
https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/controls/display-pdf/
not working for me. It says
_**The webpage at file:///android_asset/pdfjs/web/viewer.html?file=file:///android_asset/Content/abc.pdf might be temporarily down or it may have moved permanently to a new web address. **_
Someone please suggest me some easy solution or plugin for this problem. If there is any plugin working for cross platform solution free/paid please suggest.
The type or namespace name 'Android' does not exist in the namespace 'Xamarin.Forms.Platform'
Hi guys.
I Updated my nuget packages few days ago to new versions.
but my Android project has 2 errors in MainActivity.cs:
1:
The type or namespace name 'Android' does not exist in the namespace 'Xamarin.Forms.Platform' (are you missing an assembly reference?) Sama.SamaApp.Android MainActivity.cs
2:
'MainActivity.OnCreate(Bundle)': no suitable method found to override MainActivity.cs
i search it in google and find solutions.
But i tested all solutions in two up links but not worked for me.
i tested clear nuget and dotnet caches . removing bin & obj folders . restore nuget packages . remove and reinstall Xamarin.Forms .finally clean rebuilding the solution.
But I could not fix it.
thanks...
Tasks don't run asynchronously
Hi, i have a problem, after pressing button i have a simple "timeout" while loop. It should, for 10 seconds, wait for connection task to complete, but task completes after while loop ends Nothing happens while loop runs.
namespace wdw_mobile_client
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
private bool? isConnected = null;
private bool loggedIn = false;
private HttpClient _client;
public User student;
private ActivityIndicator activityIndicator;
public static NavigationPage page;
public DateTimeOffset startTime;
Task connection;
public LoginPage ()
{
InitializeComponent ();
_client = new HttpClient();
activityIndicator = indicator;
}
protected override void OnAppearing()
{
base.OnAppearing();
connection = hasConnection();
}
private async void LoginBtn_Clicked(object sender, EventArgs e)
{
loginBtn.IsEnabled = false;
//string id = student_id.Text;
//string pass = password.Text;
string id = "developer";
string pass = "developer";
string jsonString = $"{{ \"username\":\"{id}\", \"password\":\"{pass}\" }}";
DateTimeOffset startTime = DateTimeOffset.Now;
while (DateTimeOffset.Now.Subtract(startTime).TotalMilliseconds < 10000 & isConnected == null)
{
if (connection.IsCompleted)
{
student_id.IsEnabled = false;
password.IsEnabled = false;
await getToken(jsonString);
if (loggedIn)
{
page = new NavigationPage(new LectureListPage(student));
App.Current.MainPage = page;
}
}
}
loginBtn.IsEnabled = true;
await DisplayAlert("Powiadomienie", "Brak połączenia z internetem.", "OK");
}
public async Task hasConnection()
{
try {
HttpResponseMessage response = await _client.GetAsync("xxxx://xxxx.xxxxxxxxx.xxx/");
isConnected = true;
Console.WriteLine("Connected!");
}
catch(Exception e)
{
isConnected = false;
Console.WriteLine("No connection! \n" + e);
}
}
public async Task getToken(dynamic jsonString)
{
indicator.IsRunning = true;
try
{
var stringContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsync("xxxx://xxxxxx.xxxxxxxxxx.xxx/xxxxx_xxxxx", stringContent);
response.EnsureSuccessStatusCode();
string responseJson = await response.Content.ReadAsStringAsync();
student = JsonConvert.DeserializeObject<User>(responseJson);
loggedIn = true;
//Console.WriteLine("This is the token: " + student.token);
}
catch(HttpRequestException e)
{
await DisplayAlert("Błąd", "Niepoprawny nr. indeksu lub hasło.", "OK");
Console.WriteLine("Wrong id or password! \n" + e);
loginBtn.IsEnabled = true;
student_id.IsEnabled = true;
password.IsEnabled = true;
}
catch (JsonReaderException e)
{
Console.WriteLine("Json error! \n" + e);
}
indicator.IsRunning = false;
}
private void NextEntry(object sender, EventArgs e)
{
password.Focus();
}
}
}
How do I change the Resource Dictionary values programmatically?
I have this in my App.Xaml
<OnPlatform x:Key="XFactor" x:TypeArguments="x:Double">
<On Platform="iOS" Value="0.25" />
<On Platform="Android,UWP" Value="0.26" />
</OnPlatform>```
I want to change the iOS value to 0.00 on the fly in the Code.
I added this the App_Start but no effect.
Here's is the code.
This is in the App.Xaml.cs
protected override void OnStart()
{
// Handle when your app starts
Application.Current.Resources["XFactor"] = 0.00;
}```
Any ideas?