Use torch while scanning barcode - xamarin.forms

I'm using ZXing.Mobile.Forms to scan the barcodes.
I would like to turn the torch on while scanning the barcodes. I tried ToggleTorch() but i dont see the torch light.
Please help to overcome this scenario.
Here is my code:
var scanner = new ZXing.Mobile.MobileBarcodeScanner();
scanner.ToggleTorch();
var option = new ZXing.Mobile.MobileBarcodeScanningOptions { UseCode39ExtendedMode = true, TryHarder = true, PureBarcode = true, };
var result = await scanner.Scan(option);
if (result != null)
await Application.Current.MainPage.DisplayAlert(title, result.Text, "Cancel");
await Application.Current.MainPage.Navigation.PopAsync(true);

OK here is the main idea which does what you want, in an MVVM manner:
XAML:
<zxing:ZXingScannerView x:Name="ScannerView"
IsTorchOn="{Binding IsTorchOn}"
IsScanning="{Binding IsScanning}"
IsAnalyzing="{Binding IsAnalyzing}"
ScanResultCommand="{Binding OnScanResult}"/>
Code-behind:
public partial class BarcodeScannerPage
{
private BarcodeScannerPageModel _pageModel;
public BarcodeScannerPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
if(_pageModel == null) return;
_pageModel.IsScanning = true;
_pageModel.IsAnalyzing = true;
_pageModel.IsTorchOn= true;
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
_pageModel = BindingContext as BarcodeScannerPageModel;
}
}
Page model:
public class BarcodeScannerPageModel
{
#region instance variables
private bool _isScanning;
private bool _isAnalyzing;
private bool _isTorchOn;
#endregion
public BarcodeScannerPageModel()
{
IsTorchOn = true;
}
public bool IsScanning
{
get => _isScanning;
set
{
_isScanning = value;
RaisePropertyChanged();
}
}
public bool IsAnalyzing
{
get => _isAnalyzing;
set
{
_isAnalyzing = value;
RaisePropertyChanged();
}
}
public ICommand OnScanResult
{
get
{
return new Command(async (result) =>
{
if (result.ToString().IsNullOrEmpty()) return;
Device.BeginInvokeOnMainThread(async () =>
{
IsAnalyzing = false;
//your code here...
});
});
}
}
public bool IsTorchOn
{
get => _isTorchOn;
set
{
_isTorchOn = value;
RaisePropertyChanged();
}
}
}
Here I assumed MVVM is set and used correctly including "PropertyChanged" events and setting "BindingContext". More info:
MVVM
From Data Bindings to MVVM
MVVM & Data Binding with Xamarin.Forms
Using some MVVM frameworks such as FreshMvvm can make things easier.

Related

Change children pages data according to Tabbed page toolbar picker value change in Xamarin Forms

I have a Tabbed page in my Xamarin Forms app. There I have two children content pages. There are two pickers and a button in the toolbar of the Tabbed page. What I want is to populate data from the server according to the values, which is changing in the pickers. I am using the MVVM design pattern. How can I pass picker values to the children pages? I tried to use the MessagingCenter, It works sometimes but not all the time.
Tabbedpage
public partial class LifekpiRankingTabbedRM : ZeroTabbarHeight
{
public LifekpiRankingTabbedRM(string uRegion)
{
InitializeComponent();
BindingContext = new LifekpiRankingRmTabbedViewModel(uRegion);
Children.Add(new LifeKpiRankingViewRM(uRegion));
Children.Add(new LifeKpiRankingViewRMsBM(uRegion));
}
}
Tabbedpage VM
public class LifekpiRankingRmTabbedViewModel : BaseViewModelHelper
{
public MonthData2 SelectedMonth
{
get => _selectedMonth;
set
{
_selectedMonth = value;
GenerateData(_selectedMonth.mIndex, SelectedKpi).Await(CompletedTask, ErrorHandle);
OnPropertyChanged();
}
}
public string SelectedKpi
{
get => _selectedKpi;
set
{
_selectedKpi = value;
GenerateData(SelectedMonth.mIndex, _selectedKpi).Await(CompletedTask, ErrorHandle);
OnPropertyChanged();
}
}
public LifekpiRankingRmTabbedViewModel(string uRegion)
{
this.uRegion = uRegion;
SelectedMonth = GetCurrentMonth();
SelectedKpi = KpiList.First();
reportType = "Monthly";
ReportTypeTapCommand = new Command(ChangeTypeCommand);
}
private async Task GenerateData(int selectedMonth, string selectedKpi)
{
AcrDialogClass.ShowLoadingDialog("Loading...");
if (runCount > 2)
{
var resRmData = await _apiServices.GetLifeRegionalKpiWiseRanking(selectedMonth, selectedKpi, isCumulative);
var resBmForRmData = await _apiServices.GetLifeBranchKpiWiseRankingForRM(selectedMonth, selectedKpi, uRegion, isCumulative);
if (resRmData != null)
{
MessagingCenter.Send<App, string>(App.Current as App, "KPI_REGINAL_RANKING", resRmData);
}
if (resBmForRmData != null)
{
MessagingCenter.Send<App, string>(App.Current as App, "KPI_BM_RANKING_FOR_RM", resBmForRmData);
}
}
else
{
runCount++;
}
}
private MonthData2 GetCurrentMonth()
{
var months = Enumerable.Range(1, 12).Select(i => new { I = i, M = DateTimeFormatInfo.InvariantInfo.GetMonthName(i) });
foreach (var ss in months)
{
MonthList.Add(new MonthData2() { mIndex = ss.I, mName = ss.M });
}
return MonthList.Find(r => r.mIndex == dt.Month);
}
private void ChangeTypeCommand()
{
if (isCumulative)
{
reportType = "Monthly";
isCumulative = false;
}
else
{
reportType = "Cumulative";
isCumulative = true;
}
GenerateData(SelectedMonth.mIndex, SelectedKpi).Await(CompletedTask, ErrorHandle);
}
private void CompletedTask()
{
AcrDialogClass.HideLoadingDialog();
}
private void ErrorHandle(Exception ex)
{
AcrDialogClass.HideLoadingDialog();
}
}
Tab 1
public partial class LifeKpiRankingViewRM : ContentPage
{
private LifeKpiRankingViewModelRM vm;
public LifeKpiRankingViewRM(string uRegion)
{
InitializeComponent();
BindingContext = new LifeKpiRankingViewModelRM(uRegion);
vm = BindingContext as LifeKpiRankingViewModelRM;
}
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Subscribe<App, string>(App.Current, "KPI_REGINAL_RANKING", (snd, arg) =>
{
vm.SetValues(arg);
});
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Unsubscribe<App, string>(App.Current, "KPI_REGINAL_RANKING");
}
}
Tab 2
public partial class LifeKpiRankingViewRMsBM : ContentPage
{
private LifeKpiRankingViewModelBMForRM vm;
public LifeKpiRankingViewRMsBM(string uRegion)
{
InitializeComponent();
BindingContext = new LifeKpiRankingViewModelBMForRM(uRegion);
vm = BindingContext as LifeKpiRankingViewModelBMForRM;
}
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Subscribe<App, string>(App.Current, "KPI_BM_RANKING_FOR_RM", (snd, arg) =>
{
vm.SetValues(arg);
});
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Unsubscribe<App, string>(App.Current, "KPI_BM_RANKING_FOR_RM");
}
}
At first, you can try to get the child page's instance and then set its value.
If you set the tabbedpage in the app.cs with MainPage = new LifekpiRankingTabbedRM():
var tabbedpage = App.Current.MainPage as LifekpiRankingTabbedRM;
var childpage1 = tabbedpage.Children[0];
var vm1 = childpage1.BindingContext as LifeKpiRankingViewModelRM;
vm1.SetValues(...);
Generally speaking, when you have the instance of the TabbedPage, you can get its child page and update the child page's value.
In addition, you can show more details about the MessageCenter not work and we can help you go on using the MessageCenter.

MVVM Media Plugin not displaying picture

i need help with media plugin. I can see that the picture is taken however it doesnt display inthe content page. While debugging the app i can see the path but the picture is not there I have tried to follow this solution, Xamarin Forms MVVM (Prism) with Media.Plugin - How to get a taken picture from device storage
And this solution
Capturing and updating an image source using MVVM in Xamarin
however still nothing. My Binding works fine for everything. Just I dont know how to get the image
<Image
x:Name="Photo"
Grid.Row="2"
HeightRequest="100"
Source="{Binding postViewModel.ImageSource}"
VerticalOptions="Start" />
ViewModel
Ctor
public PostViewModel()
{
TakePictureCommand = new Command(async () => await TakePicture());
}
private async Task TakePicture()
{
await Permission();
var imageSource = await DependencyService.Get<IMessage>().ShowActionSheet(AppResources.AlertPhoto, AppResources.AlertNewPhoto, AppResources.AlertGallery);
if (imageSource == AppResources.AlertNewPhoto)
{
var imageFileName = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions()
{
Name = $"{DateTime.UtcNow}.jpg",
DefaultCamera = Plugin.Media.Abstractions.CameraDevice.Rear,
PhotoSize = PhotoSize.Medium,
SaveToAlbum = true
});
if (imageFileName == null)
{
DependencyService.Get<IMessage>().LongAlert(AppResources.AlertNoAcess);
}
else
{
ImageSource = ImageSource.FromStream(() => imageFileName.GetStream());
var test = ImageSource;
}
}
Master VM BInding
protected override void OnAppearing()
{
base.OnAppearing();
BindingContext = MasterPostsView= new MasterPostsViewModel();
}
class MasterPostsViewModel : BaseViewModel
{
public PostViewModel postViewModel { get; set; }
public CategoriesViewModel categoriesViewModel { get; set; }
public MasterPostsViewModel(INavigation navigation)
{
postViewModel = new PostViewModel();
categoriesViewModel = new CategoriesViewModel();
}
}
Have tried also
public string ImageSource { get => _imageSource; set { _imageSource = value; OnPropertyChanged(); } }
ImageSource = imageFileName.AlbumPath;
I have
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Xamarin Firebase and Syncfusion DataGrid. How do I listen for Firebase changes?

I'm having trouble with the coding to properly listen for Firebase add or update events. My attempt below has the data loading into the Syncfusion Datagrid, but there is a weird glitch where when I click the mouse on the Datagrid and pull-down, the first record in my 4 record set gets added to the bottom of the Datagrid, showing a 5th record... if I update an element in the Datagrid, the change is not reflected in Firebase. If I add or change a value in firebase, it does not update in Datagrid. Any help to steer me in the right direction to get this to work would be appreciated. Here's the code:
the VisualStudio 2019
CookPage.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:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Chart_sample"
xmlns:gauge="clr-namespace:Syncfusion.SfGauge.XForms;assembly=Syncfusion.SfGauge.XForms"
xmlns:Syncfusion="clr-namespace:Syncfusion.SfDataGrid.XForms;assembly=Syncfusion.SfDataGrid.XForms"
mc:Ignorable="d"
x:Class="Chart_sample.Views.CookPage">
<StackLayout>
<Syncfusion:SfDataGrid x:Name="sfGrid">
</Syncfusion:SfDataGrid>
</StackLayout>
</ContentPage>
CookPage.xaml.cs
using Chart_sample.Services;
using Syncfusion.SfDataGrid.XForms;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Chart_sample.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CookPage : ContentPage
{
FirebaseHelper firebaseHelper = new FirebaseHelper();
public CookPage()
{
InitializeComponent();
// for Syncfusion DataGrid
firebaseHelper.listenForEvents();
sfGrid.ItemsSource = ViewProgramModel._returnedEvents;
sfGrid.ColumnSizer = ColumnSizer.Star;
sfGrid.AllowEditing = true;
sfGrid.NavigationMode = NavigationMode.Cell;
sfGrid.SelectionMode = Syncfusion.SfDataGrid.XForms.SelectionMode.Single;
}
}
}
FirebaseHelper.cs
using Firebase.Database;
using Firebase.Database.Query;
using System;
using System.Linq;
namespace Chart_sample.Services
{
public class FirebaseHelper
{
internal ViewProgramModel ViewProgramModel { get; set; }
FirebaseClient firebase = new FirebaseClient("https://pelletpirate.firebaseio.com/");
private readonly string ChildProgram = "ControllerData/Pellet_Pirate_1/Program";
public static IDisposable returnedEvents;
public async void listenForEvents()
{
ViewProgramModel._returnedEvents.Clear();
var programs = await firebase.Child(ChildProgram).OnceAsync<ViewProgramModel>();
for (int i = 0; i < programs.Count; i++)
{
ViewProgramModel._returnedEvents.Add(programs.ElementAt(i).Object);
}
returnedEvents = firebase.Child(ChildProgram).OrderByKey().AsObservable<ViewProgramModel>()
.Subscribe(eventReceived =>
{
if (eventReceived.EventType == Firebase.Database.Streaming.FirebaseEventType.InsertOrUpdate)
{
var found = ViewProgramModel._returnedEvents.FirstOrDefault(i => i._KEY == eventReceived.Key);
if (found == null)
{
// not in observable collection, add it
ViewProgramModel._returnedEvents.Add(eventReceived.Object);
}
else
{
// event was updated
int tempIndex = ViewProgramModel._returnedEvents.IndexOf(found);
ViewProgramModel._returnedEvents[tempIndex] = eventReceived.Object;
}
}
});
}
}
}
ViewProgrammodel.cs
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace Chart_sample
{
public class ViewProgramModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _KEy;
private string MOde;
private int TArget;
private string TRigger;
private int TRiggerVAlue;
public string _KEY
{
get { return _KEy; }
set
{
this._KEy = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("_KEY"));
}
}
public string MODE
{
get { return MOde; }
set
{
this.MOde = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("MODE"));
}
}
public int TARGET
{
get { return TArget; }
set
{
this.TArget = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TARGET"));
}
}
public string TRIGGER
{
get { return TRigger; }
set
{
this.TRigger = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TRIGGER"));
}
}
public int TRIGGERVALUE
{
get { return TRiggerVAlue; }
set
{
this.TRiggerVAlue = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TRIGGERVALUE"));
}
}
public static ObservableCollection<ViewProgramModel> _returnedEvents = new ObservableCollection<ViewProgramModel>();
}
}
I edit your demo, I achieve the update, Add, delete function.
Here is running GIF.
I change your ViewProgramModel like following code. Just move the _returnedEvents to the FirebaseHelper.cs
namespace Chart_sample
{
public class ViewProgramModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _KEy;
private string MOde;
private int TArget;
private string TRigger;
private int TRiggerVAlue;
public string _KEY
{
get { return _KEy; }
set
{
this._KEy = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("_KEY"));
}
}
public string MODE
{
get { return MOde; }
set
{
this.MOde = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("MODE"));
}
}
public int TARGET
{
get { return TArget; }
set
{
this.TArget = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TARGET"));
}
}
public string TRIGGER
{
get { return TRigger; }
set
{
this.TRigger = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TRIGGER"));
}
}
public int TRIGGERVALUE
{
get { return TRiggerVAlue; }
set
{
this.TRiggerVAlue = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TRIGGERVALUE"));
}
}
}
Here is FirebaseHelper.cs, Note: I achieve the update function just for the TARGET Column, I suggest your to add a Primary-key(Auto-increase) for every record in your database to achieve your search function.
public class FirebaseHelper
{
public ObservableCollection<ViewProgramModel> _returnedEvents { get; set; }
public FirebaseHelper()
{
_returnedEvents = new ObservableCollection<ViewProgramModel>();
}
// internal ViewProgramModel MyViewProgramModel { get; set; }
FirebaseClient firebase = new FirebaseClient("https://xxxxxxxxxx.firebaseio.com/");
private readonly string ChildProgram = "ControllerData/xxxxxx_Pirate_1/Program";
public static IDisposable returnedEvents;
public async Task AddViewProgramModel()
{
//new ViewProgramModel() { MODE="test", TARGET=122, TRIGGER="122", TRIGGERVALUE=333, }
await firebase
.Child(ChildProgram)
.PostAsync( new ViewProgramModel() { MODE = "test", TARGET = 122, TRIGGER = "122", TRIGGERVALUE = 333, });
GetAllData();
}
public async Task UpdateViewProgramModel(ViewProgramModel viewProgramModel , string oldValue)
{
var toUpdatePerson = (await firebase
.Child(ChildProgram)
.OnceAsync<ViewProgramModel>()).FirstOrDefault(a => a.Object.TARGET == Convert.ToInt32( oldValue));
await firebase
.Child(ChildProgram)
.Child(toUpdatePerson.Key)
.PutAsync(viewProgramModel);
GetAllData();
}
public async Task DeleteViewProgramModel(string mode)
{
var toDeletePerson = (await firebase
.Child(ChildProgram)
.OnceAsync<ViewProgramModel>()).FirstOrDefault(a => a.Object.MODE == mode);
await firebase.Child(ChildProgram).Child(toDeletePerson.Key).DeleteAsync();
GetAllData();
}
public async void GetAllData()
{
_returnedEvents.Clear();
var programs = await firebase.Child(ChildProgram).OnceAsync<ViewProgramModel>();
for (int i = 0; i < programs.Count; i++)
{
_returnedEvents.Add(programs.ElementAt(i).Object);
}
}
public async void listenForEvents()
{
_returnedEvents.Clear();
var programs = await firebase.Child(ChildProgram).OnceAsync<ViewProgramModel>();
for (int i = 0; i < programs.Count; i++)
{
_returnedEvents.Add(programs.ElementAt(i).Object);
}
//returnedEvents = firebase.Child(ChildProgram).OrderByKey().AsObservable<ViewProgramModel>()
// .Subscribe(eventReceived =>
// {
// if (eventReceived.EventType == Firebase.Database.Streaming.FirebaseEventType.InsertOrUpdate)
// {
// var found = _returnedEvents.FirstOrDefault(i => i._KEY == eventReceived.Key);
// if (found == null)
// {
// // not in observable collection, add it
// _returnedEvents.Add(eventReceived.Object);
// }
// else
// {
// // event was updated
// int tempIndex = _returnedEvents.IndexOf(found);
// _returnedEvents[tempIndex] = eventReceived.Object;
// }
// }
//});
}
}
}
Here is CookPage.xaml
<StackLayout>
<Button Text="add" Clicked="Button_Clicked"></Button>
<Button Text="delete" Clicked="Button_Clicked_1"></Button>
<Syncfusion:SfDataGrid x:Name="sfGrid" ItemsSource="{Binding _returnedEvents, Mode=TwoWay} " >
</Syncfusion:SfDataGrid>
</StackLayout>
Here is code about CookPage.cs.
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CookPage : ContentPage
{
FirebaseHelper firebaseHelper = new FirebaseHelper();
public CookPage()
{
InitializeComponent();
// for Syncfusion DataGrid
firebaseHelper.listenForEvents();
//sfGrid.ItemsSource = ViewProgramModel._returnedEvents;
BindingContext= firebaseHelper;
sfGrid.ColumnSizer = ColumnSizer.Star;
sfGrid.AllowEditing = true;
sfGrid.NavigationMode = NavigationMode.Cell;
sfGrid.AllowLoadMore = true;
sfGrid.AutoGenerateColumns = true;
//sfGrid.AutoGenerateColumnsMode= AutoGenerateColumnsMode.
sfGrid.SelectionMode = Syncfusion.SfDataGrid.XForms.SelectionMode.Single;
sfGrid.AllowPullToRefresh = true;
sfGrid.CurrentCellEndEdit += SfGrid_CurrentCellEndEdit; ;
}
private async void SfGrid_CurrentCellEndEdit(object sender, GridCurrentCellEndEditEventArgs e)
{
//throw new System.NotImplementedException();
var selectObj = sender as SfDataGrid;
RowColumnIndex index = e.RowColumnIndex;
int selectColumnIndex = index.ColumnIndex; //2
int selectRowIndex = index.RowIndex; //3
var ob=firebaseHelper._returnedEvents;
ViewProgramModel selectObject =ob[selectRowIndex-1];
var newVale = e.NewValue.ToString();
var oldeValue = e.OldValue.ToString();
//Here just judge TARGET Column, you should judge all Columns
if (selectColumnIndex == 2)
{
selectObject.TARGET = Convert.ToInt32(newVale);
}
//If you want to achieve the all Grid change function, you should judge the selectRowIndex for every change
//if (selectRowIndex==1)
//{
// selectObject.MODE = newVale;
//}else if (selectRowIndex==2)
//{
// selectObject.TARGET = Convert.ToInt32( newVale);
//}else if (selectRowIndex == 3)
//{
// selectObject.TRIGGER = newVale;
//}else if (selectRowIndex == 4)
//{
// selectObject.TRIGGERVALUE = Convert.ToInt32(newVale);
//}
await firebaseHelper.UpdateViewProgramModel(selectObject, oldeValue);
}
private async void Button_Clicked(object sender, System.EventArgs e)
{
await firebaseHelper.AddViewProgramModel();
}
private async void Button_Clicked_1(object sender, System.EventArgs e)
{
await firebaseHelper.DeleteViewProgramModel("test");
}
}

Custom Control parameters binding order

pardon the cross-posting in the xamarin forum, but no one answers me there.
Some time ago I was looking for a Repeater-like control in XF, and I finally get this http://www.qimata.com/?p=7671, very simple indeed. I then started the usual "why don't add this, why don't add that" and so I added other properties and templates. Now, the control works very well for now, but I have a problem (apart from this, I don't think that is the best way to handle this scenario, if you have advice please share your thoughts).
All the logic is in the ItemsChanged event, that fires when ItemSource property is bound. Now, if I don't write the property for last, when event fires the other are yet to be evaluated. For example, this
<local:RepeaterView ShowSeparator="false" ItemsSource="{Binding itemsource}">
is not the same of
<local:RepeaterView ItemsSource="{Binding itemsource}" ShowSeparator="false">
Only in the first case property ShowSeparator has the expected value, because ItemsChanged fires before parameter initialization. Now, caring about parameters' order is not acceptable, then how can I handle this in a more decently manner?
public class RepeaterView : StackLayout
{
public static readonly BindableProperty ItemTemplateProperty = BindableProperty.Create(nameof(ItemTemplate), typeof(DataTemplate), typeof(RepeaterView), default(DataTemplate));
public static readonly BindableProperty HeaderTemplateProperty = BindableProperty.Create(nameof(HeaderTemplate), typeof(DataTemplate), typeof(RepeaterView), default(DataTemplate));
public static readonly BindableProperty EmptyTextTemplateProperty = BindableProperty.Create(nameof(EmptyTextTemplate), typeof(DataTemplate), typeof(RepeaterView), default(DataTemplate));
public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(nameof(ItemsSource), typeof(ICollection), typeof(RepeaterView), new List<object>(), BindingMode.OneWay, null, propertyChanged: (bindable, oldValue, newValue) => { ItemsChanged(bindable, (ICollection)oldValue, (ICollection)newValue); });
public static readonly BindableProperty EmptyTextProperty = BindableProperty.Create(nameof(EmptyText), typeof(string), typeof(RepeaterView), string.Empty);
public static readonly BindableProperty SelectedItemCommandProperty = BindableProperty.Create(nameof(SelectedItemCommand), typeof(ICommand), typeof(RepeaterView), default(ICommand));
public ICollection ItemsSource
{
get { return (ICollection)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public DataTemplate ItemTemplate
{
get { return (DataTemplate)GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
public DataTemplate HeaderTemplate
{
get { return (DataTemplate)GetValue(HeaderTemplateProperty); }
set { SetValue(HeaderTemplateProperty, value); }
}
public DataTemplate EmptyTextTemplate
{
get { return (DataTemplate)GetValue(EmptyTextTemplateProperty); }
set { SetValue(EmptyTextTemplateProperty, value); }
}
public string EmptyText
{
get { return (string)GetValue(EmptyTextProperty); }
set { SetValue(EmptyTextProperty, value); }
}
public ICommand SelectedItemCommand
{
get { return (ICommand)GetValue(SelectedItemCommandProperty); }
set { SetValue(SelectedItemCommandProperty, value); }
}
public bool ShowSeparator { get; set; } = true;
private static void ItemsChanged(BindableObject bindable, ICollection oldValue, ICollection newValue)
{
var repeater = (RepeaterView)bindable;
repeater.Children.Clear();
var headerTemplate = repeater.HeaderTemplate;
if (headerTemplate != null)
{
var content = headerTemplate.CreateContent();
if (!(content is View) && !(content is ViewCell))
{
//throws exception
}
var view = (content is View) ? content as View : ((ViewCell)content).View;
repeater.Children.Add(view);
repeater.Children.Add(new Divider());
}
if (newValue.Count == 0 && (repeater.EmptyTextTemplate != null || !string.IsNullOrEmpty(repeater.EmptyText)))
{
if (repeater.EmptyTextTemplate == null)
repeater.Children.Add(new Label { Text = repeater.EmptyText });
else
{
var content = repeater.EmptyTextTemplate.CreateContent();
if (!(content is View) && !(content is ViewCell))
{
//throws exception
}
var view = (content is View) ? content as View : ((ViewCell)content).View;
repeater.Children.Add(view);
}
return;
}
var dataTemplate = repeater.ItemTemplate;
foreach (object item in newValue)
{
var content = dataTemplate.CreateContent();
if (!(content is View) && !(content is ViewCell))
{
//throws exception
}
var view = (content is View) ? content as View : ((ViewCell)content).View;
if (repeater.SelectedItemCommand != null)
{
var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += (sender, e) => { repeater.SelectedItemCommand?.Execute(item); };
view.GestureRecognizers.Add(tapGestureRecognizer);
}
view.BindingContext = item;
repeater.Children.Add(view);
if (repeater.ShowSeparator)
repeater.Children.Add(new Divider { Margin = new Thickness(5, 0) });
}
}
}
}
The best strategy here would be to make sure that the items are only calculated first, once they are really requested (like in LayoutChildren).
So in OnItemSourceChanged, you only set the ItemSource, but don't do anything further unless inizialization was already done.
Should look somewhat like this (pseude-code):
private static void ItemsChanged(...)
{
var repeater = (Repeaterview)bindable;
repeater.ItemsSource = value;
if(repeater.IsInitialized) UpdateItems();
}
private override void LayoutChildren()
{
IsInitialized = true;
UpdateItems();
}
This is the basic strategy. I'll update to the correct methods/overrides once I find the time to do so. Feel free to update this answer, if you happen to find out before me.

Multithreading accepts value and return value

Hi guys, I wrote the following code to return a pdf report. The code is based on a multi-threading sample code. Can you guys provide some feedback about it, I am new to mulit-thread.
Much appriciate !
Jeffery
public delegate void StreamResultDelegate(Stream streamResults);
public class GenerateReport
{
private StreamResultDelegate callback;
public GenerateReport(StreamResultDelegate _callback)
{
callback = _callback;
}
public void ThreadProc()
{
if (callback != null)
{
callback(Testing());
}
}
public Stream Testing()
{
var reportsService = new ReportsService();
var nameValueCollection = new NameValueCollection();
byte[] pdfReportContents = reportsService.GetReport("/Rocket.Reports/RocketReport", nameValueCollection);
var stream = new MemoryStream(pdfReportContents);
return stream;
}
}
//following
[HandleError]
public class HomeController : Controller
{
private Stream streamTesting = null;
public void StreamResultCallBack(Stream s)
{
streamTesting = s;
}
public FileStreamResult GeneratePdfReport()
{
var g = new GenerateReport(_callback: new StreamResultDelegate(StreamResultCallBack));
var t = new Thread(new ThreadStart(g.ThreadProc));
t.Start();
t.Join();
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=Rockets_List_Printout.pdf");
return new FileStreamResult(streamTesting, "application/pdf");
}}
I would suggest to use async controllers -> MSDN and stop using threads in controller methods=)
My suggestion is make a private object to store the result. It's the easiest way
update
public delegate void work_handler(Stream streamResults);
public class Report
{
public object Result = null;
private Thread workThread = new ...;
public void Work(object param)
{
this.Result = ....;
// signal finish. eg. if winapp use someControl.Invoke(signal_Handler);
// for web app use this.Session["isDone"] = true;
}
// for .net 4.0
private object param = null;
public void Work()
{
// for serial invoking
var taskOption = System.Threading.Tasks.TaskCreationOptions.LongRunning;
System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(() => {... }, taskOption);
// for multiple method parallel invoke
System.Threading.Tasks.Parallel.Invoke(() => { this.Result = genReport(param); }, () => {... }, () => {...});
}
}

Resources