Navigate to the detail page of selected item in CollectionView - maui

I am using .net MAUI . I want to navigate to a detail page of selected item in CollectionView. I have tried using selectionchanged but it opens blank page .My goal is to open a detail page of particular product that is selected. It was working in ListView but when I change it to collectionView it opens blank page. I'm attaching the relevant code , Please let me know If more information is required.
Xaml code(page 1)
<CollectionView SelectionMode="Single" x:Name="listview"
IsVisible="true" RemainingItemsThreshold="12" SelectionChanged= "listview_SelectionChanged"
ItemsLayout="VerticalGrid, 2">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="18">
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="100" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120" />
<ColumnDefinition Width="120" />
</Grid.ColumnDefinitions>
<Image Source="splash_logo.png" Grid.RowSpan="1" Grid.Column="0" Grid.Row="0"/>
<Label Text="{Binding prod_name}" TextColor="Black" FontSize="Medium" FontAttributes="Bold" Grid.Column="0" Grid.Row="1" VerticalTextAlignment="Center" HorizontalOptions="CenterAndExpand"/>
<HorizontalStackLayout Grid.Row="2" Grid.Column="0" >
<Label Text="Rs." TextColor="Black"/>
<Label Text="{Binding prod_price}" TextColor="Black" LineBreakMode="TailTruncation"/>
</HorizontalStackLayout>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
xaml.cs code
private async void listview_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.CurrentSelection != null)
{
await Navigation.PushAsync(new cataloguepage
{
BindingContext = e.CurrentSelection as csv
});
}
else
{
await DisplayAlert("Alert", "No Item Selected", "ok");
}
}
xaml code(Second page)
<ContentPage.Content>
<StackLayout Padding="15">
<Label Text="{Binding prod_name}" TextColor="Black" FontAttributes="Bold" FontSize="Large" Padding="10" HorizontalOptions="Center"/>
<Label Text="{Binding prod_img}" TextColor="#289" Padding="10" HorizontalTextAlignment="Center" FontAttributes="Bold" FontSize="Medium" HeightRequest="200" WidthRequest="100" VerticalTextAlignment="Center"/>
<Label Text="{Binding prod_price}" TextColor="Black" FontSize="Medium" HorizontalTextAlignment="Center"/>
<Label Text="{Binding prod_desc}" TextColor="Black"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>

Please try the following code:
private async void listview_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.CurrentSelection != null)
{
await Navigation.PushAsync(new cataloguepage
{
// modify code as follows
BindingContext = e.CurrentSelection.FirstOrDefault() as csv
});
}
else
{
await DisplayAlert("Alert", "No Item Selected", "ok");
}
}
Note:
The e.CurrentSelection is a IEmunerable<object> list,so we can not cast it to an object.

Maybe like this , but i don't see a Binding to the CollectionView ?
ItemsSource="{Binding csv}" ??????
private async void listview_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.CurrentSelection != null)
{
await Navigation.PushAsync(new cataloguepage
{
BindingContext = e.CurrentSelection as csv
});
}
else
{
await DisplayAlert("Alert", "No Item Selected", "ok");
}
}
in secondpage , then use selectedItem
public secondpage (csv selectedItem)
{
InitializeComponent();
BindingContext = selectedItem;
}

Related

Tap gesture with Command Parameters

I have a listview with an ItemTemplate defined as follows:
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.7*" />
<ColumnDefinition Width="0.3*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding AddressTypeName}" Grid.Column="0"/>
<Label Text=""
Grid.Column="1"
FontFamily="{StaticResource SegoeMDL2Assets}" FontSize="Medium" HorizontalOptions="End">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="OnDelete_Tapped" CommandParameter="{Binding .}"/>
</Label.GestureRecognizers>
</Label>
</Grid>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
My code behind file handles the OnDelete_Tapped as follows:
public void OnDelete_Tapped(object sender, EventArgs e)
{
viewModel.DeleteCommand.Execute(e);
viewModel.LoadAddressTypesCommand.Execute(true);
}
The EventArgs e indeed returns a EventArgs object that has the correct object in it (in my case, the correct AddressType object).
The ViewModel, has this defined:
public ICommand DeleteCommand => new Command<AddressType>(DeleteCommandExecute);
void DeleteCommandExecute(AddressType address)
{
if (IsBusy)
return;
IsBusy = true;
try
{
DataStore.DeleteAddressTypeAsync(address.Id);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
IsBusy = false;
}
}
The DeleteCommand NEVER executes. I can step through the code, but it never calls the DeleteCommand in my viewModel. The LoadAddressTypesCommand runs properly - not only from the code behind but elsewhere I have that command bound as a Command to my viewModel. Any ideas what I am doing wrong? Thanks in advance.
you could try this:
in xaml:
<TapGestureRecognizer Tapped="OnDelete_Tapped" CommandParameter="{Binding .}"/>
then e.Parameter will be whatever you set in the CommandParameter.
public void OnDelete_Tapped(object sender, TappedEventArgs e)
{
var addressType = (e.Parameter) as AddressType;
viewModel.DeleteCommand.Execute(addressType );
viewModel.LoadAddressTypesCommand.Execute(true);
}
or directly Using ICommand
<TapGestureRecognizer
Command="{Binding DeleteCommand}"
CommandParameter="{Binding .}" />

how to bind popup page button to viewmodel command property in xamarin forms

I'm new to MVVM and xamarin forms. I want to implement custom popup in mvvm and following is my code
My Viewmodel is:
public class PopupVM
{
public ICommand CancelCommand => new Command(async () =>{await
Application.Current.MainPage.Navigation.PopModalAsync();});
}
My Popuppage Xaml:`
<pages:PopupPage.Animation>
<animations:ScaleAnimation DurationIn="400"
DurationOut="300"
EasingIn="SinOut"
EasingOut="SinIn"
HasBackgroundAnimation="True"
PositionIn="Center"
PositionOut="Center"
ScaleIn="1.2"
ScaleOut="0.8" />
</pages:PopupPage.Animation>
<Grid Margin="12"
Padding="24"
BackgroundColor="White"
HorizontalOptions="Center"
VerticalOptions="Center">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackLayout Orientation="Vertical">
<Picker Grid.Row="0" Grid.Column="0">
<Picker.Items>
<x:String>....</x:String>
</Picker.Items>
</Picker>
<StackLayout Orientation="Vertical" Grid.Column="0" Grid.Row="1">
<StackLayout Orientation="Horizontal" >
<Label Text="A"/>**strong text**
<Picker>
<Picker.Items>
<x:String>Item1</x:String>
<x:String>Item2</x:String>
<x:String>Item3</x:String>
</Picker.Items>
</Picker>
</StackLayout>
<StackLayout Orientation="Horizontal" >
<Label Text="B"/>
<Picker>
<Picker.Items>
<x:String>....</x:String>
</Picker.Items>
</Picker>
</StackLayout>
<StackLayout Orientation="Horizontal" >
<Label Text="C"/>
<Picker>
<Picker.Items>
<x:String>....</x:String>
</Picker.Items>
</Picker>
</StackLayout>
</StackLayout>
<Button Text="Ok"/>
<Button Text="Cancel" x:Name="cnclBtn" />
</StackLayout>
</Grid>
My Popupxaml.cs page is:
public partial class MyPopupPage
{
static PopupVM vm;
public MyPopupPage ()
{
InitializeComponent ();
if (vm==null)
{ vm = new PopupVM(); }
BindingContext = vm;
}
}
I'm not getting where im making mistake. and also i need custom popup not the default display alert
<Button Text="Cancel" x:Name="cnclBtn" Command="{binding CancelCommand}" />
For more info with commands and binding go to this

Xamarin Forms MVVM UWP ListView Binding doesn't work

I am trying to implement a MVVM ContentPage with a ListView that needs to bind to a populated generic list of XML model objects in a ViewModel but the binding fails. The code that is shown calls an API that does return a valid list of XML data. The same code works fine when the binding is done directly in the code behind of the XAML Xamarin contentpage by setting the ItemSource in the codebehind. As said, the problem only happens when trying to pass the ListView through the ViewModel assigned to the contentpage. I have stepped through the code in the ViewModel and the ListView is populated successfully but the binding just doesn't work. I have other controls that are on the page that the model binding does work for but the only control that doesn't work is the ListView. The code is shown below:
ViewModel:
using RestDemo.Model;
using RestDemo.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.ComponentModel;
using System.Windows.Input;
using System.Collections.ObjectModel;
namespace RestDemo.ViewModel
{
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ViewModel ()
{
GetRequest();
}
List<XmlPizzaDetails> _objPizzaList;
string _selectedDescription = "Descriptions: ";
bool _progress;
string _cusButtonText = "Hello";
public bool Progress
{
get { return _progress; }
set { _progress = value; }
}
public string CusButtonText
{
get { return _cusButtonText; }
set { _cusButtonText = value; }
}
public string SelectedDescription
{
get { return _selectedDescription; }
set { _selectedDescription = value; }
}
public List<XmlPizzaDetails> ObjPizzaList
{
get { return _objPizzaList; }
set
{
if (_objPizzaList != value)
{
_objPizzaList = value;
OnPropertyChanged("ObjPizzaList");
}
}
}
public string Description
{
get { return _selectedDescription; }
set { _selectedDescription = value; }
}
public ICommand SelectedCommand => new Command(() =>
{
CusButtonText = "Goodby";
});
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add
{
}
remove
{
}
}
public async void GetRequest()
{
if (NetworkCheck.IsInternet())
{
Uri geturi = new Uri("http://api.androidhive.info/pizza/?format=xml"); //replace your xml url
HttpClient client = new HttpClient();
HttpResponseMessage responseGet = await client.GetAsync(geturi);
string response = await responseGet.Content.ReadAsStringAsync();
//Xml Parsing
ObjPizzaList = new List<XmlPizzaDetails>();
XDocument doc = XDocument.Parse(response);
foreach (var item in doc.Descendants("item"))
{
XmlPizzaDetails ObjPizzaItem = new XmlPizzaDetails();
ObjPizzaItem.ID = item.Element("id").Value.ToString();
ObjPizzaItem.Name = item.Element("name").Value.ToString();
ObjPizzaItem.Cost = item.Element("cost").Value.ToString();
ObjPizzaItem.Description = item.Element("description").Value.ToString();
ObjPizzaList.Add(ObjPizzaItem);
}
Progress = false;
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
}
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:xlocal="clr-namespace:RestDemo.ViewModel"
xmlns:local="clr-namespace:RestDemo"
xmlns:Views="clr-namespace:RestDemo.Views"
x:Class="RestDemo.XmlParsingPageBehavior">
<ContentPage.BindingContext>
<xlocal:ViewModel />
</ContentPage.BindingContext>
<Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Views:CustomButton Grid.Row="0" Grid.Column="0" Text="HOME" />
<Views:CustomButton Grid.Row="0" Grid.Column="1" Text="Administrative Maintence" />
<Views:CustomButton Grid.Row="0" Grid.Column="2" Text="User Maintence" />
<Views:CustomButton Grid.Row="0" Grid.Column="3" Text="About" />
</Grid>
<Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Views:CustomButton Grid.Row="0" Grid.Column="0" Text="{Binding CusButtonText, Mode=TwoWay}">
<Views:CustomButton.Behaviors>
<local:ItemSelectedToCommandBehavior />
</Views:CustomButton.Behaviors>
</Views:CustomButton>
</Grid>
<Frame Margin="5, 5, 5, 5" Grid.Row="2" Grid.Column="1" BackgroundColor = "Cyan">
<ListView x:Name="PizzaListView" ItemsSource="{Binding ObjPizzaList}" Margin="5, 0, 5, 0" Grid.Row="2" Grid.Column="1" HorizontalOptions="FillAndExpand" HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid HorizontalOptions="FillAndExpand" Margin="0,0,0,0" Padding="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Text="{Binding Name}" HorizontalOptions="StartAndExpand" Grid.Row="0" TextColor="Blue" FontAttributes="Bold"/>
<Label Text="{Binding Cost}" HorizontalOptions="StartAndExpand" Grid.Row="1" TextColor="Orange" FontAttributes="Bold"/>
<Label Text="{Binding Description}" HorizontalOptions="StartAndExpand" Grid.Row="2" TextColor="Gray" FontAttributes="Bold"/>
<BoxView HeightRequest="2" Margin="0,10,10,0" BackgroundColor="Gray" Grid.Row="3" HorizontalOptions="Fill" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Frame>
</Grid>
<ActivityIndicator x:Name="ProgressLoader" IsVisible="{Binding Progress}" IsRunning="True"/>
</Grid>
</ContentPage>
I have it working. Yes ObservableCollections are the way to go but generic Lists are fine as well. The problem is that when the Model is bound the WebService call has not completed so when the List property is bound it is still null. Even when updated at this point the ObservableCollection won't work because it has not been seeded. The solution is to seed the ObservableCollection, or List, on the Page's OnAppearing event and bind the ViewModel as the BindingContext in this event. My solution is below:
protected override async void OnAppearing()
{
var vm = new ViewModel.ViewModel();
if (vm == null)
return;
HttpClient client = new HttpClient();
HttpResponseMessage responseGet = await client.GetAsync(vm.Geturi);
string response = await responseGet.Content.ReadAsStringAsync();
//Xml Parsing
var _objPizzaList = new ObservableCollection<XmlPizzaDetails>();
XDocument doc = XDocument.Parse(response);
vm.GetRequest(doc);
this.BindingContext = vm;
}

MVVM, using Multiple DataSets and Multiple ComboBoxes tied to each other

I have a single Database EstimateInformationTable with CATEGORY, DESCRIPTION. 100 records total. There are 100 Descriptions and 10 Categories, so obviously the Categories are used more than once.
example:
+----------+-------------+
| CATEGORY | DESCRIPTION |
+----------+-------------+
| ACC | DescAAAA |
| ACC | DescBBBB |
| BMX | DescCCCC |
+----------+-------------+
I want to use the first ComboBox (CATEGORY) to limit the choices in the second ComboBox (DESCRIPTION).
I have two ComboBoxes bound to two DataSet TableAdaptors. Each TableAdaptor returns a simple, but different Schema.
ComboBox1:
SELECT DISTINCT CATEGORY
FROM EstimateInformationTable
ORDER BY CATEGORY
ComboBox2:
SELECT DESCRIPTION
FROM EstimateInformationTable
WHERE (CATEGORY = #Category)
ORDER BY DESCRIPTION
I can kind of get this to work in CodeBehind using an extra ButtonClickEvent, but obviously this is not ultimately what I want.
I want to use MVVM and the correct Notify Properties (if that is what needs to be done) so that changing the Category ComboBox updates the Description ComboBox.
This must be done all the time, but I am new to a lot of this. I was making progress, but I am having a hard time wrapping my head around this. This is a self imposed learning exercise, so feel free to dumb the explanation down for me. Thanks, mike
XAML:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:gobo.Pages"
xmlns:gobo="clr-namespace:gobo" x:Class="gobo.Pages.TESTSTUFF01"
xmlns:vm="clr-namespace:gobo.ViewModel"
mc:Ignorable="d"
Title="TESTSTUFF01" Loaded="Page_Loaded">
<Page.Resources>
<vm:CategoryChangedViewModel x:Key="CategoryChangedViewModel"/>
<gobo:gobo2018DataSet1 x:Key="gobo2018DataSet1"/>
<CollectionViewSource x:Key="estimateInformationTableViewSource" Source="{Binding EstimateInformationTable, Source={StaticResource gobo2018DataSet1}}"/>
<gobo:gobo2018EstimateInformationTableDescriptionDataSet x:Key="gobo2018EstimateInformationTableDescriptionDataSet"/>
<CollectionViewSource x:Key="estimateInformationTableViewSource1" Source="{Binding EstimateInformationTable, Source={StaticResource gobo2018EstimateInformationTableDescriptionDataSet}}"/>
</Page.Resources>
<Page.Background>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="Red" Offset="1"/>
</LinearGradientBrush>
</Page.Background>
<StackPanel Orientation="Vertical" >
<Label Content="TEST STUFF 01 Tab Page1" VerticalAlignment="Top" Background="{x:Null}"/>
<Button Content="Change Description contents" Click="Button_Click"/>
<Grid x:Name="grid1" DataContext="{StaticResource estimateInformationTableViewSource}" HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Content="CATEGORY:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="0" VerticalAlignment="Center"/>
<ComboBox x:Name="cATEGORYComboBox" Grid.Column="1" DisplayMemberPath="CATEGORY" HorizontalAlignment="Left" Height="Auto" Margin="3" Grid.Row="0" VerticalAlignment="Center" Width="120"
ItemsSource="{Binding}"
SelectedIndex="{Binding Category, Source={StaticResource CategoryChangedViewModel}}">
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
</Grid>
<Grid x:Name="grid2" DataContext="{StaticResource estimateInformationTableViewSource1}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="311">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Content="DESCRIPTION:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="0" VerticalAlignment="Center"/>
<ComboBox x:Name="dESCRIPTIONComboBox" Grid.Column="1" DisplayMemberPath="DESCRIPTION" HorizontalAlignment="Left" Height="Auto" ItemsSource="{Binding}" Margin="3,9,-53,9" Grid.Row="0" VerticalAlignment="Center" Width="180">
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
</Grid>
</StackPanel>
</Page>
CurrentCodeBehind
namespace gobo.Pages
{
/// <summary>
/// Interaction logic for TESTSTUFF01.xaml
/// </summary>
public partial class TESTSTUFF01 : Page
{
private gobo.gobo2018DataSet1 gobo2018DataSet1;
public gobo.gobo2018DataSet1TableAdapters.EstimateInformationTableTableAdapter gobo2018DataSet1TableAdapter;
private CollectionViewSource estimateInformationTableViewSource;
private gobo.gobo2018EstimateInformationTableDescriptionDataSet gobo2018EstimateInformationTableDescriptionDataSet;
private gobo.gobo2018EstimateInformationTableDescriptionDataSetTableAdapters.EstimateInformationTableTableAdapter EstimateInformationTableTableAdapter;
private CollectionViewSource estimateInformationTableViewSource1;
public TESTSTUFF01()
{
InitializeComponent();
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
gobo2018DataSet1 = ((gobo.gobo2018DataSet1)(this.FindResource("gobo2018DataSet1")));
gobo2018DataSet1TableAdapter = new gobo.gobo2018DataSet1TableAdapters.EstimateInformationTableTableAdapter();
gobo2018DataSet1TableAdapter.Fill(gobo2018DataSet1.EstimateInformationTable);
estimateInformationTableViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("estimateInformationTableViewSource")));
estimateInformationTableViewSource.View.MoveCurrentToFirst();
gobo2018EstimateInformationTableDescriptionDataSet = ((gobo.gobo2018EstimateInformationTableDescriptionDataSet)(this.FindResource("gobo2018EstimateInformationTableDescriptionDataSet")));
EstimateInformationTableTableAdapter = new gobo.gobo2018EstimateInformationTableDescriptionDataSetTableAdapters.EstimateInformationTableTableAdapter();
EstimateInformationTableTableAdapter.FillByCategory(gobo2018EstimateInformationTableDescriptionDataSet.EstimateInformationTable,"ACC");
estimateInformationTableViewSource1 = ((System.Windows.Data.CollectionViewSource)(this.FindResource("estimateInformationTableViewSource1")));
estimateInformationTableViewSource1.View.MoveCurrentToFirst();
}
public void LoadDescriptionToCbo(String parameter)
{
if(gobo2018EstimateInformationTableDescriptionDataSet != null)
{
EstimateInformationTableTableAdapter.FillByCategory(gobo2018EstimateInformationTableDescriptionDataSet.EstimateInformationTable, parameter);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
LoadDescriptionToCbo("ACT");
Console.WriteLine("Button Click -> LoadDescriptionToCode");
}
}
}
I've found that this works, but I am curious if it is the best answer.
private void cATEGORYComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox cbx = (ComboBox)sender;
string s = ((DataRowView)cbx.Items.GetItemAt(cbx.SelectedIndex)).Row.ItemArray[0].ToString();
LoadDescriptionToCbo(s);
}

One click handler for multiple buttons in stackpanel

I have following xaml:
<GroupBox x:Name="GroupBoxInworp" IsEnabled="True" Header="Inworp" HorizontalAlignment="Stretch" Margin="10,120,10,0" VerticalAlignment="Top" VerticalContentAlignment="Stretch">
<StackPanel x:Name="StackPanelInworp" Button.Click="button_Click">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0">
<Button x:Name="btnTweeEuro" Margin="10" MinWidth="220" Content="2" Click="btnTweeEuro_Click"></Button>
<Button x:Name="btnEenEuro" Margin="10" MinWidth="220" Content="1" Click="btnEenEuro_Click"></Button>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0">
<Button x:Name="btnVijftigEurocent" Margin="10" MinWidth="100" Content="50" Click="btnVijftigEurocent_Click"></Button>
<Button x:Name="btnTwintigEurocent" Margin="10" MinWidth="100" Content="20" Click="btnTwintigEurocent_Click"></Button>
<Button x:Name="btnTienEurocent" Margin="10" MinWidth="100" Content="10" Click="btnTienEurocent_Click"></Button>
<Button x:Name="btnVijfEurocent" Margin="10" MinWidth="100" Content="5" Click="btnVijfEurocent_Click"></Button>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="5">
<Label Content="Huidige inworp:" MinWidth="160"></Label>
<Label x:Name="lblHuidigeInworp" Content="" MinWidth="300" HorizontalContentAlignment="Right"></Label>
</StackPanel>
</StackPanel>
</GroupBox>
I have following code:
private void GeldClick(decimal Inworp)
{
TotaalInworp += Inworp;
lblHuidigeInworp.Content = String.Format("€ {0}", TotaalInworp);
}
private void btnTweeEuro_Click(object sender, RoutedEventArgs e)
{
GeldClick(2.00M);
}
private void btnEenEuro_Click(object sender, RoutedEventArgs e)
{
GeldClick(1.00M);
}
private void btnVijftigEurocent_Click(object sender, RoutedEventArgs e)
{
GeldClick(0.50M);
}
private void btnTwintigEurocent_Click(object sender, RoutedEventArgs e)
{
GeldClick(0.20M);
}
private void btnTienEurocent_Click(object sender, RoutedEventArgs e)
{
GeldClick(0.10M);
}
private void btnVijfEurocent_Click(object sender, RoutedEventArgs e)
{
GeldClick(0.05M);
}
I want to create one handler for all click events with a for or a switch.
The handler would be like
StackPanelInworp.AddHandler(Button.ClickEvent, new RoutedEventHandler(button_Click));
I also want to create a class, in which i can place the event handler with the for or switch. There are 6 buttons.
How can this be accomplished? Also, it concerns decimals so a switch would be impossible i think?
I came up with this:
Xaml
<StackPanel x:Name="StackPanelInworp">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0">
<Button x:Name="btnTweeEuro" Margin="10" MinWidth="220" Content="2" Click="btnGeld_Click"></Button>
<Button x:Name="btnEenEuro" Margin="10" MinWidth="220" Content="1" Click="btnGeld_Click"></Button>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0">
<Button x:Name="btnVijftigEurocent" Margin="10" MinWidth="100" Content="50" Click="btnGeld_Click"></Button>
<Button x:Name="btnTwintigEurocent" Margin="10" MinWidth="100" Content="20" Click="btnGeld_Click"></Button>
<Button x:Name="btnTienEurocent" Margin="10" MinWidth="100" Content="10" Click="btnGeld_Click"></Button>
<Button x:Name="btnVijfEurocent" Margin="10" MinWidth="100" Content="5" Click="btnGeld_Click"></Button>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="5">
<Label Content="Huidige inworp:" MinWidth="160"></Label>
<Label x:Name="lblHuidigeInworp" Content="" MinWidth="300" HorizontalContentAlignment="Right"></Label>
</StackPanel>
</StackPanel>
Code:
//Methode voor uitvoeren van alle click events mbt Geld
private void GeldClick(decimal Inworp)
{
TotaalInworp += Inworp;
lblHuidigeInworp.Content = String.Format("€ {0}", TotaalInworp);
}
//Enkel click event voor alle knoppen mbt Drank
private void btnGeld_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
switch (btn.Content.ToString())
{
case "2":
GeldClick(2.00M);
break;
case "1":
GeldClick(1.00M);
break;
case "50":
GeldClick(0.50M);
break;
case "20":
GeldClick(0.20M);
break;
case "10":
GeldClick(0.10M);
break;
case "5":
GeldClick(0.05M);
break;
}
}
Anyone knows improvements? Wanted to work with the stackpanelname for the buttons but don't know how to ...