I followed the below tutorial
https://xamarinhelp.com/use-camera-take-photo-xamarin-forms/
(I installed version 3.1.3)
But I get this error:
CS0103 The name 'PhotoImage' does not exist in the current context
In this method:
private async void CameraButton_Clicked(object sender, EventArgs e)
{
var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new plugin.Media.Abstractions.StoreCameraMediaOptions() { });
if (photo != null)
PhotoImage.Source = ImageSource.FromStream(() => { return photo.GetStream(); });
}
I am new to Xamarin and am not sure how to fix this.
From shared sample , you can have a check whether Xaml contains PhotoImage :
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image x:Name="PhotoImage" />
<Button x:Name="CameraButton" Text="Take Photo" Grid.Row="1" />
</Grid>
Related
I want to set focus on SearchBar when he appears. The problem is that SearchBar is placed inside of popup view and I need to access him from ViewModel.
In standard way I would use
Xamarin.Forms.SearchBar tmp_SearchBar = this.Page.FindByName("fro_SearchBar_NewItem") as Xamarin.Forms.SearchBar;
but that's not working anymore.
Here is XAML
<sfPopup:SfPopupLayout x:Name="fro_Popup_NewItem" Opened="fro_Popup_NewItem_Opened" Grid.Row="1" HorizontalOptions="Center" VerticalOptions="Center" BackgroundColor="Black">
<sfPopup:SfPopupLayout.PopupView>
<sfPopup:PopupView BackgroundColor="Black" WidthRequest ="400" HeightRequest ="100" ShowFooter="False" ShowHeader="False">
<sfPopup:PopupView.ContentTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!--Search bar-->
<Grid Grid.Row="0" HorizontalOptions="Center" VerticalOptions="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<SearchBar x:Name="fro_SearchBar_NewItem"
Grid.Column="0"
Text="{Binding SearchText_Popup, Mode=TwoWay}"
SearchCommand="{Binding SearchCommand}"
Placeholder="Find"
CancelButtonColor="White"
TextColor="White"
PlaceholderColor="Gray"/>
</Grid>
</Grid>
</DataTemplate>
</sfPopup:PopupView.ContentTemplate>
</sfPopup:PopupView>
</sfPopup:SfPopupLayout.PopupView>
</sfPopup:SfPopupLayout>
Nested FindByName doesn't work either.
Syncfusion.XForms.PopupLayout.SfPopupLayout tmp_Popup = _Page.FindByName("fro_Popup_NewItem") as Syncfusion.XForms.PopupLayout.SfPopupLayout;
Xamarin.Forms.SearchBar tmp_SearchBar = tmp_Popup.FindByName("fro_SearchBar_NewItem") as Xamarin.Forms.SearchBar;
Thanks
You can use Task to open a new thread to complete this operation in code-behind.
Xaml:
<SearchBar x:Name="fro_SearchBar_NewItem" Placeholder="...." BackgroundColor="White"/>
Code behind:
public partial class PagePop : Popup
{
public PagePop()
{
InitializeComponent();
Task.Run(() => myTask());//Create and start the thread
}
private void myTask()
{
Thread.Sleep(300);
fro_SearchBar_NewItem.Focus();
}
}
It seems that this wasn't so far from right direction, neither of the comments actually.
Syncfusion.XForms.PopupLayout.SfPopupLayout tmp_Popup = _Page.FindByName("fro_Popup_NewItem") as Syncfusion.XForms.PopupLayout.SfPopupLayout;
Xamarin.Forms.SearchBar tmp_SearchBar = tmp_Popup.FindByName("fro_SearchBar_NewItem") as Xamarin.Forms.SearchBar;
but I found the one which works and I don't have to create separate XAML for Popup.
private void fro_Popup_NewItem_Opened(object sender, EventArgs e)
{
try
{
var nativeObject = (object)fro_Popup_NewItem.GetType().GetRuntimeProperties().FirstOrDefault(x => x.Name.Equals("NativeObject")).GetValue(fro_Popup_NewItem);
var formsPopupviewContentTemplate = nativeObject.GetType().GetRuntimeFields().FirstOrDefault(x => x.Name.Equals("formsPopupViewContentTemplate")).GetValue(nativeObject);
var SearchBar = (formsPopupviewContentTemplate as Grid).FindByName<SearchBar>("fro_SearchBar_NewItem");
SearchBar?.Focus();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Thanks for help, everyone.
I want to take photo using Xamarin form custom renderer.
I use Custom Renderer Sample and I add a Button named 'btnTakePicture' in Xaml , but I don't have any idea how to take photo on Button click event.
I want to show camera in part of screen.
Also I checked Xam.Media.Plugin and I couldn't take photo.
Xaml Code
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:CustomRenderer;assembly=CustomRenderer"
x:Class="CustomRenderer.frmCamera"
Title="Main Page">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="7*"/>
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Label Text="Camera Preview"/>
</Grid>
<Grid Grid.Row="1">
<local:CameraPreview Camera="Rear" x:Name="cmrPreview"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" Background="black"/>
</Grid>
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Button x:Name="btnChangeCamera" Text="Switch Camera" Clicked="btnChangeCamera_Clicked"/>
<Button x:Name="btnTakePicture" Text="Take" Grid.Column="1" Clicked="btnTakePicture_Clicked"/>
</Grid>
<Frame></Frame>
</Grid>
</ContentPage>
C# Code
using System.IO;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace CustomRenderer
{
public partial class frmCamera : ContentPage
{
public frmCamera()
{
InitializeComponent();
}
private void btnChangeCamera_Clicked(object sender, System.EventArgs e)
{
if (cmrPreview.Camera == CameraOptions.Rear)
cmrPreview.Camera = CameraOptions.Front;
else
cmrPreview.Camera = CameraOptions.Rear;
}
bool blnIsFlashLight = false;
private void btnFlashLight_Clicked(object sender, System.EventArgs e)
{
if (blnIsFlashLight)
{
Flashlight.TurnOffAsync();
blnIsFlashLight = false;
}
else
{
Flashlight.TurnOnAsync();
blnIsFlashLight = true;
}
}
private void btnTakePhoto_Clicked(object sender, System.EventArgs e)
{
}
}
}
here is my project Screenshot
I have a button
and i want to focus an entry on button click
so my button command is:
public Command FocusPassword
{
get
{
return new Command(() =>
{
Entry myEntry= Application.Current.MainPage.FindByName<Entry>("pEntry");
passwordEntry.Focus();
});
}
}
myEntry always returning null,so how to solve this?
I simply solve this:
Page currentPage = Navigation.NavigationStack.LastOrDefault();
Entry passwordEntry = currentPage.FindByName<Entry>("PassEntry");
passwordEntry.Focus();
Is it myEntry that is null, or passwordEntry? You are assigning the returned object to myEntry but then trying to set the focus on passwordEntry:
Entry myEntry= Application.Current.MainPage.FindByName<Entry>("pEntry");
passwordEntry.Focus();
And yes, make sure that the Entry does have the x:Name set to pEntry, e.g.:
<Entry x:Name="pEntry" ... />
You could try to use my demo as well.
MainPage.xaml (Do not forget to BindingContext)
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:EntryDemo"
x:Class="EntryDemo.MainPage">
<StackLayout>
<Grid Margin="10">
<Grid.BindingContext>
<local:BindingViewModel/>
</Grid.BindingContext>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Entry
Grid.Row="0"
HorizontalOptions="CenterAndExpand"
Text="account"
x:Name="accountEntry"
/>
<Entry
Text="password"
Grid.Row="1"
HorizontalOptions="CenterAndExpand"
x:Name="pEntry"
/>
<Button
Grid.Row="2"
HorizontalOptions="CenterAndExpand"
x:Name="MyButton"
Text="FocusEntry "
Command="{Binding FocusCommand}"
/>
</Grid>
</StackLayout>
</ContentPage>
You should run FindByName in execute method
BindingViewModel.cs
public class BindingViewModel: BindableObject
{
public BindingViewModel()
{
FocusCommand = new Command(
execute: () =>
{
Entry accountEntry = Application.Current.MainPage.FindByName<Entry>("accountEntry");
Entry myEntry = Application.Current.MainPage.FindByName<Entry>("pEntry");
accountEntry.Focus();
}
);
}
public ICommand FocusCommand { private set; get; }
}
I have a ListView with a template containing an Image and a Text.
When i refresh the list, sometimes, some images are not displayed (randomly)
If i scroll down the list and scroll up to see the item again, image will appear magically, so the Image is set correctly to the item.
I tried ListViewCachingStrategy.RecycleElement and ListViewCachingStrategy.RetainElement, no difference.
<ListView ItemsSource="{Binding Path=Results}"
HasUnevenRows="True"
IsPullToRefreshEnabled="True"
RefreshCommand="{Binding RefreshCommand}"
IsRefreshing="{Binding IsBusy, Mode=OneWay}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/> <!-- Image -->
<ColumnDefinition Width="3*"/> <!-- Message -->
<ColumnDefinition Width="1*"/> <!-- Date -->
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- Image -->
<Grid Grid.Column="0" Grid.Row="0" Grid.RowSpan="3"
HorizontalOptions="FillAndExpand"
BackgroundColor="#40000000">
<Image Source="{Binding Thumbnail}"
VerticalOptions="Center"
Aspect="AspectFill"/>
</Grid>
private async Task RefreshAsync()
{
try
{
IsBusy = true;
_results.Clear();
_results.AsyncQueryStarted();
var result = await _client.QueryAsync<ReportResult>(_report);
if (result != null)
{
try
{
var items = new List<ResultItem>(result.Events.Count);
foreach (var res in result.Events)
{
result.EntityLookup.TryGetValue(res.Guid, out var name);
var item = new ResultItem(res.Guid, name, res.EventTime, res.Notes);
items.Add(item);
}
int itemWidth = (int)(PageWidth / ItemsPerRow);
// Sort them by timestamp (latest first)
foreach (var item in items.OrderByDescending(x => x.Timestamp))
{
item.ItemWidth = itemWidth;
_results.Add(item);
}
}
catch { }
_results.AsyncQueryFinished(_results.Count == 0);
RefreshView();
}
}
catch (Exception ex)
{
Application.Current.Trace("Error occured while refreshing", ex, this);
}
finally
{
_requiresRefresh = false;
IsBusy = false;
}
}
private async void RefreshView()
{
int itemWidth = (int)(PageWidth / ItemsPerRow);
var requests = new List<ThumbnailItem>();
var results = new List<ResultItem>(_results);
foreach (var item in results)
{
item.ItemWidth = itemWidth;
// Try to retrieve it from cache
item.Thumbnail = await _thumbnailService.RetrieveAsync(item.Id, null, item.Timestamp);
}
}
I have this (copied from the examples)...
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:MyApp" x:Class="MyApp.MainPage" xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.Input">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackLayout Padding="5">
<Label Text="Select a view mode" />
<Picker x:Name="viewModePicker" />
</StackLayout>
<telerikInput:RadCalendar x:Name="calendar" NativeControlLoaded="CalendarLoaded" Grid.Row="1"/>
</Grid>
</ContentPage>
And...
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
calendar.DisplayDate = new DateTime(2017, 4, 12);
viewModePicker.ItemsSource = Enum.GetValues(typeof(CalendarViewMode));
viewModePicker.SelectedItem = CalendarViewMode.Day;
viewModePicker.SelectedIndexChanged += ViewModeChanged;
}
private void ViewModeChanged(object sender, EventArgs e)
{
calendar.TrySetViewMode((CalendarViewMode)viewModePicker.SelectedItem);
}
private void CalendarLoaded(object sender, System.EventArgs e)
{
calendar.TrySetViewMode((CalendarViewMode)viewModePicker.SelectedItem);
}
}
Everything works, including the calendar instance existing, except I can't see it! I'm using an iOS app.
This rendered fine for me:
StartPage.xaml.cs
using System;
using Telerik.XamarinForms.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TelerikXamarinApp1
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class StartPage : ContentPage
{
public StartPage()
{
InitializeComponent();
calendar.DisplayDate = new DateTime(2017, 4, 12);
viewModePicker.ItemsSource = Enum.GetValues(typeof(CalendarViewMode));
viewModePicker.SelectedItem = CalendarViewMode.Day;
viewModePicker.SelectedIndexChanged += ViewModeChanged;
}
private void ViewModeChanged(object sender, EventArgs e)
{
calendar.TrySetViewMode((CalendarViewMode)viewModePicker.SelectedItem);
}
private void CalendarLoaded(object sender, EventArgs e)
{
calendar.TrySetViewMode((CalendarViewMode)viewModePicker.SelectedItem);
}
}
}
StartPage.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"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.Input"
x:Class="TelerikXamarinApp1.StartPage">
<ContentView.Content>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackLayout Padding="5">
<Label Text="Select a view mode" />
<Picker x:Name="viewModePicker" />
</StackLayout>
<telerikInput:RadCalendar x:Name="calendar" NativeControlLoaded="CalendarLoaded" Grid.Row="1" />
</Grid>
</ContentView.Content>
</ContentPage>
I reinstalled the DLLs from the Telerik Nuget server. Must have missed something, and I didn't realise that one can log on to their server using one's regular Telerik website credentials.
This resulted in the calendar appearing on my iPhone but not in the simulator. I copied my solution over to Mac OS and used Visual Studio Mac to build and deploy and now the calendar appears in the simulator too.
Also, the build and deploy time seems about twice as fast. Was using Windows on Parallels before, though.