Get the value in entry field then reflect/react to a label in xamarin form - xamarin.forms

My problem is idk how to reflect in a label depending of input value in a entry field by a customer.
To make the things clear, let's start in our database.
Our database
Few information about our realtime database.
In our DELIVERY TABLE, we have 3 types of delivery(standard, reservation and express). In express, by the word itself, it's a rush delivery and we will require a DELIVERY FEE from the customer.
Another table is PRODUCT. We have 2 product for now, MINERAL(PROD1) AND SPARKLING(PROD2). The price of PROD1 is 35 ana PROD2 is 40.
What I've try right now is I put an SelectedIndexChanged in my picker delivery type and picker product type.
//This is my deliverytype event
private async void Picker_DeliveryType_SelectedIndexChanged(object sender, EventArgs e)
{
DELIVERY deliverySave = Picker_DeliveryType.SelectedItem as DELIVERY;
var selectedDeliveryItem = deliverySave.deliveryType;
var note = deliverySave.deliveryFee;
if(selectedDeliveryItem == "Express")
{
await DisplayAlert("Note", "Estimated Delivery: 2 hours from now", "OK");
labelDeliveryFee.Text = "Delivery Fee:" + note;
entryfieldReservationDate.IsEnabled = false;
}
else if(selectedDeliveryItem == "Standard")
{
await DisplayAlert("Note", "Within the day", "OK");
entryfieldReservationDate.IsEnabled = true;
}
else
{
await DisplayAlert("Note", "Enter Reservation Date", "OK");
entryfieldReservationDate.IsEnabled = true;
}
}
//This is my product type event
private void Picker_ProductType_SelectedIndexChanged(object sender, EventArgs e)
{
PRODUCT prod = Picker_ProductType.SelectedItem as PRODUCT;
var selectedProductItem = prod.productType;
var productPricing = prod.productPrice;
if (selectedProductItem == "Mineral")
{
labelProductPrice.Text = Convert.ToString(productPricing);
}
else
{
labelProductPrice.Text = Convert.ToString(productPricing);
}
}
AND my expected output is I want the 2 SelectedIndexChanged will put inside my order button.
//this is my order button click functio now
async private void Button_Clicked(object sender, EventArgs e)
{
if (selectedDeliveryType == "Standard")
{
if (selectedProductItem == "Mineral")
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
else
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
}
else if (selectedDeliveryType == "Reservation")
{
if (selectedProductItem == "Mineral")
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
else
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
}
else
{
int deliveryfee = deliverySave.deliveryFee;
if (selectedProductItem == "Mineral")
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
else
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
}
//some code here
var SaveData = await waterorderRepos.Save(waterOrder);
var SaveDataToCustomerNotification = await waterorderRepos.SaveCustomerNotification(customerNotification);
if (SaveData)
{
await this.DisplayAlert("Order", "Order successfully", "OK");
ClearData();
CloseAllPopup();
return;
}
else
{
await this.DisplayAlert("Order", "We cannot process your order at the moment.", "OK");
}
}
I will show you some visual presentation between my work now and my expected output.
This is the image.
Please help me guys, idk how to it.Also, no MVVM please cause IDK how to do it. Thank you so much.

Based on the complexity of your code, I recommend that you use the MVVM pattern for implementation.
I created a demo and achieved your function.
You can refer to the following code:
1.create a view model MyViewModel.cs
public class MyViewModel: INotifyPropertyChanged
{
public ObservableCollection<Delivery> Deliveries { get; set; }
private Delivery _deliverySelectedItem;
public Delivery DeliverySelectedItem
{
get => _deliverySelectedItem;
set {
SetProperty(ref _deliverySelectedItem, value);
// update the TotalAmount
caculateTotalAmount();
}
}
public ObservableCollection<Product> Products { get; set; }
//add SelectedItem here
private Product _productSelectedItem;
public Product ProductSelectedItem
{
get => _productSelectedItem;
set {
SetProperty(ref _productSelectedItem, value);
// update the TotalAmount
caculateTotalAmount();
}
}
private int _quantity;
public int Quantity
{
get => _quantity;
set
{
SetProperty(ref _quantity, value);
// update the TotalAmount
caculateTotalAmount();
}
}
private int _totalAmount;
public int TotalAmount
{
get => _totalAmount;
set
{
SetProperty(ref _totalAmount, value);
}
}
private void caculateTotalAmount() {
if (String.IsNullOrEmpty(Quantity.ToString() ) || Quantity == 0) {
TotalAmount = 0;
return;
}
if (ProductSelectedItem!=null && DeliverySelectedItem!=null) {
TotalAmount = ProductSelectedItem.productPrice * Quantity + DeliverySelectedItem.deliveryFee;
}
}
public MyViewModel() {
Products = new ObservableCollection<Product>();
Products.Add(new Product { ProductId = 01, productType = "Products", productPrice = 10 });
Products.Add(new Product { ProductId = 02, productType = "02", productPrice = 12 });
Products.Add(new Product { ProductId = 03, productType = "Products", productPrice = 13 });
Products.Add(new Product { ProductId = 04, productType = "Products", productPrice = 15 });
Deliveries = new ObservableCollection<Delivery>();
Deliveries.Add(new Delivery { deliveryFee = 10, deliveryType = "Express" });
Deliveries.Add(new Delivery { deliveryFee = 20, deliveryType = "Standard" });
Deliveries.Add(new Delivery { deliveryFee = 30, deliveryType = "Standard" });
}
bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Object.Equals(storage, value))
return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
2.create class Delivery.cs and Product.cs
public class Delivery
{
public string deliveryType { get; set; }
public int deliveryFee { get; set;}
}
public class Product
{
public int ProductId { get; set; }
public string productType { get; set; }
public int productPrice { get; set; }
}
3.MainPage.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:pickerapp2023112="clr-namespace:PickerApp2023112"
x:Class="PickerApp2023112.MainPage">
<ContentPage.BindingContext>
<pickerapp2023112:MyViewModel></pickerapp2023112:MyViewModel>
</ContentPage.BindingContext>
<StackLayout>
<Picker x:Name="Picker_DeliveryType" ItemsSource="{Binding Deliveries}" ItemDisplayBinding="{Binding deliveryFee}" SelectedItem="{Binding DeliverySelectedItem}"
Title="Select a delivery type"
TitleColor="Red">
</Picker>
<Picker x:Name="Picker_ProductType" ItemsSource="{Binding Products}" ItemDisplayBinding="{Binding productPrice}" SelectedItem="{Binding ProductSelectedItem}"
Title="Select a product type"
TitleColor="Red">
</Picker>
<StackLayout Orientation="Horizontal">
<Label Text="Please input quantity: " BackgroundColor="CadetBlue"/>
<Entry Placeholder="0" Text="{Binding Quantity}" TextColor="Red" HorizontalOptions="FillAndExpand"></Entry>
</StackLayout>
<Label x:Name="labelDeliveryFee" Text="{Binding DeliverySelectedItem.deliveryFee,StringFormat='The delivery free is {0:F1}'}" HorizontalOptions="StartAndExpand" BackgroundColor="Yellow"></Label>
<Label x:Name="labelProductPrice" Text="{Binding ProductSelectedItem.productPrice,StringFormat='The product price is {0:F2}'}" HorizontalOptions="StartAndExpand" BackgroundColor="Yellow"></Label>
<StackLayout Orientation="Horizontal">
<Label Text="The total amount: " BackgroundColor="CadetBlue"/>
<Entry Placeholder="0" Text="{Binding TotalAmount}" TextColor="Red" HorizontalOptions="FillAndExpand"></Entry>
</StackLayout>
</StackLayout>
</ContentPage>
Note:
1.I add two objects for the SelectedItem property of two Pickers and implement interface INotifyPropertyChanged for this ViewModel, if we change the value of the property, the UI will update automatically. The same is true for other properties.
private Delivery _deliverySelectedItem;
public Delivery DeliverySelectedItem
{
get => _deliverySelectedItem;
set {
SetProperty(ref _deliverySelectedItem, value);
}
}
public ObservableCollection<Product> Products { get; set; }
//add SelectedItem here
private Product _productSelectedItem;
public Product ProductSelectedItem
{
get => _productSelectedItem;
set {
SetProperty(ref _productSelectedItem, value);
}
}
In this condition, we don't need add event SelectedIndexChanged for Picker.

Related

Xamarin Forms MVVM set picker SelectedItem to a value

I am new to Xamarin.Forms and MVVM. I have following picker in XAML:
<Picker Title="Marital Status"
x:Name="maritalStatus"
Margin="10,5,10,0"
ItemsSource="{Binding MaritalStatusList}"
ItemDisplayBinding="{Binding Value}"
SelectedItem="{Binding SelectedMaritalStatus, Mode=TwoWay}">
</Picker>
This is how I setup the item source:
public class KeyValuePair
{
public int Key { get; set; }
public string Value { get; set; }
}
public static class MaritalStatus
{
public static List<KeyValuePair> GetMaritalStatus()
{
return new List<KeyValuePair>()
{
new KeyValuePair() {Key=1, Value="Single"},
new KeyValuePair() {Key=1, Value="Married"},
new KeyValuePair() {Key=1, Value="Widowed"},
new KeyValuePair() {Key=1, Value="Divorced"},
new KeyValuePair() {Key=1, Value="Civil Partnership"}
};
}
}
And this is how I set the property:
KeyValuePair selectedMaritalStatus;
public KeyValuePair SelectedMaritalStatus
{
get => selectedMaritalStatus;
set
{
SetProperty(ref selectedMaritalStatus, value);
MaritalStatusText = selectedMaritalStatus.Value;
}
}
string maritalStatusText;
public string MaritalStatusText
{
get => maritalStatusText;
set
{
SetProperty(ref maritalStatusText, value);
}
}
The above displays properly the list in the picker. My problem is that I have a form and I want to set the picker to the value that comes from a database. I have some other entries that I can successfully set from a ViewModel like so:
foreach (EmployeeDetails details in EmployeeDetailsService.EmployeeDetails)
{
Id = details.Id;
ADEmployeeID = await new MSGraphService().GetUserIdAsync();
FirstName = details.FirstName;
MiddleName = details.MiddleName;
LastName = details.LastName;
Street = details.Address.Street;
Block = details.Address.Block;
City = details.Address.City;
County = details.Address.County;
PostCode = details.Address.PostCode;
Telephone = details.Telephone;
DateOfBirth = details.DateOfBirth != null ? DateTime.Parse(details.DateOfBirth) : DateTime.Now.Date;
CountryOfBirth = details.CountryOfBirth;
SelectedMaritalStatus.Value = details.MaritalStatus;
//MaritalStatusText = details.MaritalStatus;
PassportIssuingCountry = details.PassportIssuingCountry;
PassportNumber = details.PassportNumber;
PassportExpiryDate = details.PassportExpiryDate != null ? DateTime.Parse(details.PassportExpiryDate) : DateTime.Now.Date;
BankName = details.BankName;
BankAddress = details.BankAddress;
BankSortCode = details.BankSortCode;
NationalInsuranceNumber = details.NationalInsuranceNumber;
// //! Need to add P45
}
Marital Status picker is the only one that I cannot set, everything else works.
*** UPDATE ***
This is my SetProperty:
protected bool SetProperty<T>(ref T backingStore, T value,
[CallerMemberName] string propertyName = "",
Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value)) { return false; }
backingStore = value;
onChanged?.Invoke();
OnPropertyChanged(propertyName);
return true;
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChangedEventHandler changed = PropertyChanged;
if (changed == null) { return; }
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
Any help would be much appreciated.
SelectedMaritalStatus has to be one of the objects in MaritalStatusList
SelectedMaritalStatus = MaritalStatusList[0];
or
SelectedMaritalStatus = MaritalStatusList.First(x => x.ID == "some value from your db");
You could try to set defalut value of the Xamarin Picker. You just set the selectedIndex(the first number of index is 0) of your picker in yourpage.xaml.cs just as follows:
maritalStatus.SelectedIndex=1;
The whole code is:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
maritalStatus.SelectedIndex = 1;
}
// other code
}
Note:
I suggest you rename your Picker to better indentify your Picker(e.g. mStatusPicker)

Xamarin forms picker binding did not display

I want to get the data from the firebase and binding into the picker but it did not display anything.
xaml
<Picker Title="Select Category" ItemsSource="{Binding IncomeList}" ItemDisplayBinding="{Binding Name}"
Viewmodel
public class AddIncomeViewModel{
public List<Category> IncomeList { get; set; }
private FirebaseHelper services;
public AddIncomeViewModel{
service = new FirebaseHelper();
IncomeList = new List<Category>();
GetIncomeList();
}
public async void GetIncomeList()
{
try
{
List<Category> income = await services.GetIncome();
foreach (Category incomes in income)
{
IncomeList.Add(new Category
{
Name = incomes.Name,
CategoryType = incomes.CategoryType
});
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
It did not have any error but display nothing.If I add this line of code it will work fine.
IncomeList.Add(new Category
{
Name = "Salary",
CategoryType = "Income"
});
Can I know why this happen?

Xamarin datagrid not show up after OnScanResult Zxing

I can get datatable after scan barcode but it not show when i bind it to sfDatagrid. what am i doing wrong. I think i call vm.TimSPTonKho.Execute(null); in .cs incorrectly
code xaml and .cs
<ContentPage.BindingContext>
<vm:vmBanHang_get_TTSanPham_ScanCode />
</ContentPage.BindingContext>
<StackLayout>
<Grid VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand">
<zxing:ZXingScannerView x:Name="scanView"
OnScanResult="scanView_OnScanResult"
IsScanning="True"
WidthRequest="200"
HeightRequest="300"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand"/>
<zxing:ZXingDefaultOverlay TopText="Align the barcode within the frame"/>
</Grid>
<datagrid:SfDataGrid HorizontalOptions="Center" x:Name="datagrid"
AllowTriStateSorting="True"
ColumnSizer="Star"
ItemsSource="{Binding DataTableCollection}">
</datagrid:SfDataGrid>
</StackLayout>
this my xaml file
private void scanView_OnScanResult(Result result)
{
Device.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("Scanned result", "The barcode's text is " + result.Text + ". The barcode's format is " + result.BarcodeFormat, "OK");
var vm = new vmBanHang_get_TTSanPham_ScanCode();
vm.MaSanPham = result.Text;
vm.IDCuaHang = 1;
vm.TimSPTonKho.Execute(null);
});
}
my ViewModel.cs
class vmBanHang_get_TTSanPham_ScanCode : INotifyPropertyChanged
{
private ApiServices _apiServices = new ApiServices();
public int IDCuaHang { get; set; }
public string MaSanPham { get; set; }
public vmBanHang_get_TTSanPham_ScanCode()
{
DataTableCollection = _DataTableCollection;
}
public DataTable DataTableCollection
{
get { return _DataTableCollection; }
set
{
_DataTableCollection = value;
OnPropertyChanged();
}
}
public DataTable _DataTableCollection;
public ICommand TimSPTonKho
{
get
{
return new Command(async () =>
{
if (!string.IsNullOrEmpty(MaSanPham))
{
DataTableCollection = await _apiServices.get_TTSanPham_ScanCode(IDCuaHang, MaSanPham, Settings.Accesstoken);
}
});
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
2. My second question, how can i get all values Datagrid send to Datatable ? do i have to implement it in xaml.cs or in viewmodel.
Thanks for helps
I found the solution. bind directly from xaml.cs
datagrid.ItemsSource = await _apiServices.get_TTSanPham_ScanCode(1, result.Text, Settings.Accesstoken);
instead of call Icommand in Viewmodel
public ICommand TimSPTonKho
{
get
{
return new Command(async () =>
{
if (!string.IsNullOrEmpty(MaSanPham))
{
DataTableCollection = await _apiServices.get_TTSanPham_ScanCode(IDCuaHang, MaSanPham, Settings.Accesstoken);
}
});
}
}

UWP how to update a bound TextBox with changes in selected item of a bound ListView

I have a UWP Page, containing a form with textboxes and a ListView control. The ListView control is bound to a collection of Products. And I want that the bound textboxes should show the information regarding the product selected in the listview.
public class Product: INotifyPropertyChanged
{
public int ProductID { get; set; }
private string name;
public string Name {
get { return name; }
set
{
if (name==value)
return;
name = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public Product(int pid, string name)
{
ProductID = pid;
Name = name;
}
}
}
The XAML is as below:
<TextBox x:Name="txtProductId" Grid.Row="1" Grid.Column="1"
Text="{x:Bind CurrentProduct.ProductID}"/>
<TextBox x:Name="txtProductName" Grid.Row="2" Grid.Column="1"
Text="{x:Bind CurrentProduct.Name}" />
<ListView x:Name="lstProducts" Grid.Row="3" Grid.ColumnSpan="2"
ItemsSource="{x:Bind ProductList}"
SelectedItem="{x:Bind CurrentProduct, Mode=TwoWay}"
ItemTemplate="{StaticResource lstDataTemplate}"
>
</ListView>
The following code executes on Page_Loaded:
CurrentProduct = Products[0];
DataContext = CurrentProduct;
The ListView is bound to ProductList (Type ObservableCollection). I've noticed by executing the app in single step mode, the value of CurrentProduct is changing, but I think since it is the reference and not the property of the DataContext that changes, the PropertyChanged event is never fired and the TextBox doesn't get updated to show the name of the CurrentProduct.
I don't know how to proceed, any help would be appreciated.
The X:Bind default mode is OneTime, in your case, you need to set the mode to OneWay.
I made a code sample for your reference:
<TextBox x:Name="txtProductId" Grid.Row="1" Grid.Column="1"
Text="{x:Bind CurrentProduct.ProductID,Mode=OneWay}"/>
<TextBox x:Name="txtProductName" Grid.Row="2" Grid.Column="1"
Text="{x:Bind CurrentProduct.Name,Mode=OneWay}" />
<ListView x:Name="lstProducts" Grid.Row="3" Grid.ColumnSpan="2"
ItemsSource="{x:Bind ProductList}"
SelectedItem="{x:Bind CurrentProduct, Mode=TwoWay}"
>
</ListView>
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
public MainPage()
{
this.InitializeComponent();
this.Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; i++)
{
ProductList.Add(new Product(i, "name " + i));
}
}
public ObservableCollection<Product> ProductList { get; set; } = new ObservableCollection<Product>();
private Product _CurrentProduct = new Product(100,"test");
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,new PropertyChangedEventArgs(PropertyName));
}
}
public Product CurrentProduct
{
get { return _CurrentProduct; }
set
{
if (_CurrentProduct != value)
{
_CurrentProduct = value;
RaisePropertyChanged("CurrentProduct");
}
}
}
}
public class Product : INotifyPropertyChanged
{
public int ProductID { get; set; }
private string name;
public string Name
{
get { return name; }
set
{
if (name == value)
return;
name = value;
RaisePropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
public Product(int pid, string name)
{
ProductID = pid;
Name = name;
}
public override string ToString()
{
return Name;
}
}

How to refresh data grid with new search results with MVVM Light

I'm using the latest MMVM Light windows 8 binaries and VS 2012 latest updates, so all is good there. I'm new to the MVVM Light framework, so it's an adjustment.
I have a Customers page with a grid that is searched with a textbox and button - the text box is bound and the button uses a command. The data is showing up in the view model just fine. I LINQ over the Customers List and set the Customers list property - all works well. The problem is, the page doesn't refresh. When I go to another page and return to the Customers page, the searched data is displayed.
I suspect the view model is static and needs to re-instantiated.
The follow are the respective code frags:
public partial class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
}
else
{
SimpleIoc.Default.Register<IDataService, DataService>();
}
// Services
SimpleIoc.Default.Register<INavigationService, NavigationService>();
SimpleIoc.Default.Register<IMessenger, Messenger>();
// View Models
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<CustomersViewModel>();
SimpleIoc.Default.Register<CustomerViewModel>(true);
SimpleIoc.Default.Register<ContactsViewModel>();
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public CustomersViewModel Customers
{
get
{
return ServiceLocator.Current.GetInstance<CustomersViewModel>();
}
}
public CustomerViewModel Customer
{
get
{
return ServiceLocator.Current.GetInstance<CustomerViewModel>();
}
}
public ContactsViewModel Contacts
{
get
{
return ServiceLocator.Current.GetInstance<ContactsViewModel>();
}
}
public static void Cleanup()
{
}
}
}
public class CustomersViewModel : ViewModelBase
{
private readonly IDataService _dataService;
private INavigationService _navigationService;
private IMessenger _messenger;
public RelayCommand<string> RefreshClickCommand { get; set; }
public RelayCommand<string> SearchCustomersCommand { get; set; }
public const string CustomersPropertyName = "Customers";
private ObservableCollection<Customer> _customers = null;
public ObservableCollection<Customer> Customers
{
get
{
return _customers;
}
set
{
if (_customers == value)
{
return;
}
_customers = value;
RaisePropertyChanging(CustomersPropertyName);
}
}
public const string WelcomeTitlePropertyName = "WelcomeTitle";
private string _welcomeTitle = string.Empty;
public string WelcomeTitle
{
get
{
return _welcomeTitle;
}
set
{
if (_welcomeTitle == value)
{
return;
}
_welcomeTitle = value;
RaisePropertyChanged(WelcomeTitlePropertyName);
}
}
public const string CustomerSearchTermPropertyName = "CustomerSearchTerm";
private string _customerSearchTerm = string.Empty;
public string CustomerSearchTerm
{
get
{
return _customerSearchTerm;
}
set
{
if (_customerSearchTerm == value)
{
return;
}
_customerSearchTerm = value;
RaisePropertyChanging(CustomerSearchTermPropertyName);
}
}
public Customer SelectedItem
{
set
{
Customer customer = value;
_messenger.Send<Customer>(customer, "Customer");
_navigationService.Navigate(typeof(CustomerPage));
}
}
public CustomersViewModel(IDataService dataService)
{
_navigationService = SimpleIoc.Default.GetInstance<INavigationService>();
_messenger = SimpleIoc.Default.GetInstance<IMessenger>();
_dataService = dataService;
_dataService.GetData(
(item, error) =>
{
if (error != null)
{
// Report error here
return;
}
WelcomeTitle = item.Title + "Customers";
});
GetCustomers();
InitializeCommands();
}
private void InitializeCommands()
{
RefreshClickCommand = new RelayCommand<string>((item) =>
{
GetCustomers();
});
SearchCustomersCommand = new RelayCommand<string>((item) =>
{
SearchCustomers();
});
}
private void GetCustomers()
{
_customers = _dataService.GetCustomers();
}
private void SearchCustomers()
{
var cust = _dataService.GetCustomers();
List<Customer> customers = (from c in cust
where c.CompanyName.StartsWith(_customerSearchTerm)
orderby c.CompanyName
select c).ToList();
_customers = new ObservableCollection<Customer>(customers);
}
}
<common:LayoutAwarePage x:Class="SalesAccountManager.Views.RelationshipManager.CustomersPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:common="using:SalesAccountManager.Common"
xmlns:ignore="http://www.ignore.com"
xmlns:telerikGrid="using:Telerik.UI.Xaml.Controls.Grid"
xmlns:WinRtBehaviors="using:WinRtBehaviors"
xmlns:Win8nl_Behavior="using:Win8nl.Behaviors"
mc:Ignorable="d ignore"
d:DesignHeight="768"
d:DesignWidth="1366"
DataContext="{Binding Customers, Source={StaticResource Locator}}">
....
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<TextBlock Text="Customers" FontFamily="Segoe UI" FontSize="38"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0, 0, 100, 0">
<TextBox Height="20" Width="600" Background="White" Text="{Binding CustomerSearchTerm, Mode=TwoWay}" />
<Button Background="White" Command="{Binding SearchCustomersCommand}">
<Image Source="../../Images/Search.jpg" Height="20" Width="20"></Image>
</Button>
</StackPanel>
</Grid>
Any guidance on this would be appreciated...
Thanks!

Resources