How to assign List<> Object values to textBox (s) - c#

I want to assign the values of the findFamily object to the different TextBox(s) i tried the following code but it's not working would you please suggest me a better way. Thanks in advance.
private void Search_Click(object sender, RoutedEventArgs e)
{
if (SearchFamilyMemberId.Text.Trim() != "")
{
SITDataDataContext con = new SITDataDataContext();
List<Family> findFamily = (from s in con.Families where s.FamilyMemberId.Equals(SearchFamilyMemberId.Text.Trim()) select s).ToList();
if (findFamily.Any())
{
FamilyMemberId.Text = findFamily[0];
FirstName.Text = findFamily[1];
LastName.Text = findFamily[2];
if (findFamily[3]=="Male")
{
Male.IsChecked = true;
}
else
{
Female.IsChecked = true;
}
Phone.Text = findFamily[4];
Address.Text = findFamily[5];
}
else
{
MessageBox.Show("Family Id not found!");
}
}
else
{
MessageBox.Show("Invalid Id!");
}
}
here is my xamal code
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="1" Grid.Column="0" Content="Family Member ID:"/>
<Label Grid.Row="2" Grid.Column="0" Content="First Name:"/>
<Label Grid.Row="3" Grid.Column="0" Content="Last Name:"/>
<Label Grid.Row="4" Grid.Column="0" Content="Gender:"/>
<Label Grid.Row="5" Grid.Column="0" Content="Phone:"/>
<Label Grid.Row="6" Grid.Column="0" Content="Address:"/>
<CheckBox Name="ColonyResident" Content="Colony Resident" Grid.Row="0" Grid.Column="0" Margin="5" Checked="ColonyResident_Checked" Unchecked="ColonyResident_Unchecked"/>
<TextBox Name="SearchFamilyMemberId" IsEnabled="False" SelectionChanged="FamilyMemberId_SelectionChanged" Grid.Row="0" Grid.Column="1" Margin="3"/>
<TextBox Name="FamilyMemberId" IsEnabled="False" Grid.Row="1" Grid.Column="1" Margin="3" Grid.ColumnSpan="2"/>
<TextBox Name="FirstName" Grid.Row="2" Grid.Column="1" Margin="3" Grid.ColumnSpan="2"/>
<TextBox Name="LastName" Grid.Row="3" Grid.Column="1" Margin="3" Grid.ColumnSpan="2"/>
<RadioButton Name="Male" Grid.Row="4" Grid.Column="1" Margin="3" Content="Male" />
<RadioButton Name="Female" Grid.Row="4" Grid.Column="2" Margin="3" Content="Female" />
<TextBox Name="Phone" Grid.Row="5" Grid.Column="1" Margin="3" Grid.ColumnSpan="2"/>
<TextBox Name="Address" Grid.Row="6" Grid.Column="1" Margin="3" Grid.ColumnSpan="2" TextWrapping="Wrap"/>
<Button Name="Search" IsEnabled="False" Grid.Row="0" Grid.Column="2" Margin="3" MinWidth="100" MinHeight="25" HorizontalAlignment="Center" Content="Search" Click="Search_Click"/>
<Button IsDefault="True" Grid.Row="7" Grid.Column="1" Margin="3" MinWidth="100" MinHeight="25" HorizontalAlignment="Center" Content="Add" Click="Add_Click"/>
<Button Grid.Row="7" Grid.Column="2" Margin="3" MinWidth="100" MinHeight="25" HorizontalAlignment="Center" Content="Clear" Click="Clear_Click"/>
</Grid>

Why don't you use data binding?
For each of the text boxes that you have, bind your TextBox.Text to its corresponding property in the view model, something like this:
<TextBox Text={Binding FirstName} />
Then, assign your FirstName, LastName...etc. properties to values and raise INotifyPropertyChanged.PropertyChanged for each of the properties (your view model should implement INotifyPropertyChanged) and your view (i.e. UI) should get updated.

I don't agree with any of the answers posted here. The question doesn't seem to be correct.
If you have a list of Family members. Then how can you show it as a single item. How do you know which item you want to display.
Hence my suggestion is to use a listbox and using data binding, create a view to display the current selected Family member's data in that view.

use foreach loop through list as:
foreach(var a in findFamily)
{
txtbox.text=a[0].tostring();
txtbox2.text=a[1].tostring();
}
or use:
txtbox.text = findFamily.Select(a => a[0].ToString()).FirstOrDefault().ToString();

Related

WPF bind TextBlock "text" in one user control to textbox in another UserControl Where both of them are hosted in a Frame inside mainWindow

SUMMARY OF THE PROBLEM:
I have main window which has a frame and a button, in the frame i'm going to show one user control at a time (i provided an image of my usercontrol).
in the first UserControl, i will write 4 player names (two for each team).
after i press the button and i go to next usercontrol i want to show the names of the players in textblock. I also want to bind IsChecked property of radio button in first UserControl to the second UserControl. (i have other buttons that show up in mainWindow depends on what usercontrol is in the Frame right Now)
WHAT I TRIED:
I tried binding the textbox property to the textblock in the second usercontrol but it doesnt show or i cant access it.
because i have the button in the mainWindow i tried saving the names in variable then pass it to next usercontrol but didnt work also.
Also tried alot of random online solution i found online but nothing worked.
i need a way to expose the property of First UserControl to be used in the Second UserControl
MY CODE
MainWindow xaml
<Grid SnapsToDevicePixels="True" x:Name="myGrid" >
<Grid.Background>
<ImageBrush x:Name="myBackground" ImageSource="background1.png" Stretch="UniformToFill"/>
</Grid.Background>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="300" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="*" />
<RowDefinition Height=" auto" />
<RowDefinition Height=" 20" />
</Grid.RowDefinitions>
<Frame x:Name="Main" Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" Grid.ColumnSpan="5" NavigationUIVisibility="Hidden" >
</Frame>
<Button Style="{StaticResource StandardButton}" Visibility="Visible" x:Name="playersBtn" Grid.Column="2" Grid.Row ="2" Margin="100,40,100,40" FontSize="36" Content="إبدأ" FontFamily="Ara Hamah Homs" Padding="50,0" Background="#FFFFE900" Click="playerInfoBtn" BorderBrush="{x:Null}" Foreground="Black" >
</Button>
MainWindow c#
namespace Try3
{
public partial class MainWindow : Window
{
SoundPlayer MP = new SoundPlayer();
public MainWindow()
{
InitializeComponent();
MP.SoundLocation = "C:/Users/eadh2/Desktop/game tries/try3/try3/sound1.wav";
MP.PlayLooping();
}
private void playerInfoBtn(object sender, RoutedEventArgs e)
{
Main.Content = new PlayersInfoPage();
playersBtn.Visibility = Visibility.Hidden;
startBtn.Visibility = Visibility.Visible;
icon.Visibility = Visibility.Collapsed;
ImageBrush b = new ImageBrush();
b.ImageSource = new BitmapImage(new Uri("pack://application:,,,/background flat.png"));
myGrid.Background = b;
}
private void startBtn_Click(object sender, RoutedEventArgs e)
{
Main.Content = new gamePage();
startBtn.Visibility = Visibility.Collapsed;
gamePageBoarder.Visibility = Visibility.Visible;
}
private void startBtn_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
startBtn.Background = Brushes.DarkGreen;
}
}
}
First usercontrol xaml to enter player names (Image of First UserControl to enter player names)
<UserControl x:Class="Try3.PlayersInfoPage"
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:Try3"
mc:Ignorable="d"
d:DesignHeight="862.179" d:DesignWidth="1210.632" >
<Grid SnapsToDevicePixels="True">
<Grid.ColumnDefinitions >
<ColumnDefinition Width="150" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width=" *" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="AUTO" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="100" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height=" *" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<TextBlock Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="2" Text="بيانات الفريق الأحمر" FontSize="36" Margin="50,0,50,0" FontFamily="Ara Hamah Homs" />
<TextBox x:Name="redFirst" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Margin="0,30,0,20" Padding="10" FontSize="36" HorizontalContentAlignment="Center" Text="اللاعب الأول" Foreground="#FF919191" GotMouseCapture="redFirst_GotMouseCapture" FontFamily="Ara Hamah Homs" />
<TextBox x:Name="redSecond" Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="2" Margin="0,30,0,110" Padding="10" FontSize="36" HorizontalContentAlignment="Center" Text="اللاعب الثاني" Foreground="#FF919191" GotMouseCapture="redSecond_GotMouseCapture1" FontFamily="Ara Hamah Homs" />
<TextBlock Grid.Column="4" Grid.Row="1" Grid.ColumnSpan="2" Text="بيانات الفريق الأخضر " FontSize="36" Margin="50,0,50,20" FontFamily="Ara Hamah Homs" />
<TextBox x:Name="greenFirst" Grid.Row="2" Grid.Column="4" Grid.ColumnSpan="2" Margin="0,30,0,20" Padding="10" FontSize="36" HorizontalContentAlignment="Center" Text="اللاعب الأول" Foreground="#FF919191" GotMouseCapture="greenFirst_GotMouseCapture2" FontFamily="Ara Hamah Homs" />
<TextBox x:Name="greenSecond" Grid.Row="3" Grid.Column="4" Grid.ColumnSpan="2" Margin="0,30,0,110" Padding="10" FontSize="36" HorizontalContentAlignment="Center" Text="اللاعب الثاني" Foreground="#FF919191" GotMouseCapture="greenSecond_GotMouseCapture3" FontFamily="Ara Hamah Homs" />
<Border x:Name="roundsBoarder" Grid.Column="3" Grid.Row="2" Grid.RowSpan="2" BorderThickness ="3" BorderBrush="Black" CornerRadius="0" Margin="20,50,20,130" MaxHeight="170" MaxWidth="350" VerticalAlignment="Center" Background="#99FFFFFF" MouseEnter="Border_MouseEnter" MouseLeave="roundsBoarder_MouseLeave">
<StackPanel HorizontalAlignment="Center" >
<StackPanel Orientation="Horizontal" >
<Viewbox Height="40" Width="40" >
<RadioButton BorderBrush="#FFFFE900" VerticalContentAlignment="Center" HorizontalAlignment="Left" GroupName="roundsNumber" FontFamily="Ara Hamah Homs" FontSize="12"/>
</Viewbox>
<TextBlock Text="جولة" FontSize="42" Margin="20,0,0,0" FontFamily="Alnaqaaa R" />
</StackPanel>
<StackPanel Orientation="Horizontal" >
<Viewbox Height="40" Width="40" >
<RadioButton BorderBrush="#FFFFE900" VerticalContentAlignment="Center" HorizontalAlignment="Left" GroupName="roundsNumber" FontFamily="Ara Hamah Homs" FontSize="12"/>
</Viewbox>
<TextBlock Text="ثلاث جولات" FontSize="42" Margin="20,0,0,0" FontFamily="Alnaqaaa R" />
</StackPanel>
</StackPanel>
</Border>
</Grid>
First UserControl C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Try3
{
public partial class PlayersInfoPage : UserControl
{
public PlayersInfoPage()
{
InitializeComponent();
}
private void redFirst_GotMouseCapture(object sender, MouseEventArgs e)
{
redFirst.Text = "";
redFirst.Foreground = Brushes.Black;
}
private void redSecond_GotMouseCapture1(object sender, MouseEventArgs e)
{
redSecond.Text = "";
redSecond.Foreground = Brushes.Black;
}
private void greenFirst_GotMouseCapture2(object sender, MouseEventArgs e)
{
greenFirst.Text = "";
greenFirst.Foreground = Brushes.Black;
}
private void greenSecond_GotMouseCapture3(object sender, MouseEventArgs e)
{
greenSecond.Text = "";
greenSecond.Foreground = Brushes.Black;
}
private void Save_MouseEnter(object sender, MouseEventArgs e)
{
}
private void Save_MouseLeave(object sender, MouseEventArgs e)
{
}
private void Border_MouseEnter(object sender, MouseEventArgs e)
{
roundsBoarder.Background = new SolidColorBrush(Colors.White) { Opacity = 1 };
roundsBoarder.CornerRadius = new CornerRadius(20);
}
private void roundsBoarder_MouseLeave(object sender, MouseEventArgs e)
{
roundsBoarder.Background = new SolidColorBrush(Colors.White) { Opacity = 0.6 };
roundsBoarder.CornerRadius = new CornerRadius(0);
}
}
}
Second UserControl xaml to show player names in each side
<UserControl x:Class="Try3.gamePage"
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:try3"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.ColumnDefinitions >
<ColumnDefinition Width="50" />
<ColumnDefinition Width="60" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="60" />
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions >
<RowDefinition Height="50" />
<RowDefinition Height="*" />
<RowDefinition Height="auto" />
<RowDefinition Height="50" />
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<StackPanel Orientation="Vertical" Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="1" >
<TextBlock HorizontalAlignment="Center" FontSize="36" FontFamily="Ara Hamah Homs" Text="الفريق الأحمر" />
<TextBlock x:Name="redFirstPlayer" FontSize="24" FontFamily="Ara Hamah Homs" Text="اللاعب الاول" HorizontalAlignment="Center"/>
<TextBlock x:Name="redSecondPlayer" FontSize="24" FontFamily="Ara Hamah Homs" Text="اللاعب الثاني" HorizontalAlignment="Center"/>
</StackPanel>
<StackPanel Orientation="Vertical" Grid.Column="6" Grid.ColumnSpan="2" Grid.Row="1">
<TextBlock FontSize="36" FontFamily="Ara Hamah Homs" Text="الفريق الأخضر" HorizontalAlignment="Center" Margin="0,0,0,20"/>
<TextBlock x:Name="greenFirstPlayer" FontSize="24" FontFamily="Ara Hamah Homs" Text="اللاعب الاول" HorizontalAlignment="Center"/>
<TextBlock x:Name="greenSecondPlayer" FontSize="24" FontFamily="Ara Hamah Homs" Text="اللاعب الثاني" HorizontalAlignment="Center"/>
</StackPanel>
<TextBlock x:Name="redScore" Grid.Column="1" Grid.Row="3" FontSize="42" FontFamily="Ara Hamah Homs" Text="0" HorizontalAlignment="center" />
<Image Source="trophy (1).png" Grid.Column="2" Grid.Row="3" HorizontalAlignment="Left"/>
<TextBlock x:Name="greenScore" Grid.Column="7" Grid.Row="3" FontSize="42" FontFamily="Ara Hamah Homs" HorizontalAlignment="center" Text="0" />
<Image Source="trophy (1).png" Grid.Column="6" Grid.Row="3" HorizontalAlignment="Right"/>
<StackPanel Grid.Row="1" Grid.Column="6" Grid.ColumnSpan="2" Margin="0,50,0,0" >
</StackPanel>
</Grid>

Xamarin - ListView showing all property values but one

I have a Content Page in which I want to show an invoice, for that I have two listviews.
The first one contains the name of the customer, the date and the total cost.
The thing is to get the total cost I have used Shell navigation with parameters and it works fine just not in the listview.
So here is my ViewModel
[QueryProperty(nameof(Total), "total")]
public class InvoiceViewModel : BindableObject
{
string _total;
public string Total
{
get => _total;
set
{
_total = Uri.UnescapeDataString(value ?? string.Empty);
OnPropertyChanged();
}
}
public InvoiceViewModel()
{
_oListOrders = new ObservableCollection<CrOrder>();
GetListCart();
}
private ApiService _apiService = new ApiService();
public List<Invoice> _oListCart = new List<Invoice>();
public ObservableCollection<CrOrder> _oListOrders;
public List<Invoice> ListCart
{
get => _oListCart;
set
{
_oListCart = value;
OnPropertyChanged();
}
}
private async void GetListCart()
{
// call database here
var customerId = Convert.ToInt32(CurrentPropertiesService.GetCustomer());
var customer = await _apiService.GetCustomerById(customerId, CurrentPropertiesService.GetToken());
_oListCart.Add(new Invoice
{
Name = customer.Data.Name,
Date = DateTime.UtcNow,
Total = Convert.ToDecimal(_total),
ListOrders = await GetListOrders()
});
}
private async Task<ObservableCollection<CrOrder>> GetListOrders()
{
// call database here
var cartId = Convert.ToInt32(CurrentPropertiesService.GetCart());
var orders = await _apiService.GetOrdersByCart(cartId, CurrentPropertiesService.GetToken());
ObservableCollection<CrOrder> collection = new ObservableCollection<CrOrder>(orders.Data);
return collection;
}
}
Here is what I have in my View
<ContentPage.Content>
<StackLayout BackgroundColor="#A7A7A7">
<Label Text="{Binding Total}" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"></Label>
<ListView x:Name="ListViewCart" ItemsSource="{Binding ListCart}" HasUnevenRows="True" IsPullToRefreshEnabled="False" >
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:Invoice">
<ViewCell>
<Frame HasShadow="True" Margin="2" BorderColor="Gray">
<Grid Margin="0" HorizontalOptions="FillAndExpand" VerticalOptions="Center" HeightRequest="150" RowSpacing="0" ColumnSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Text="Nombre del Cliente:" VerticalOptions="Start"/>
<Label Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding Name}" VerticalOptions="Start"/>
<Label Grid.Row="1" Grid.Column="0" Text="Fecha Compra:" VerticalOptions="Start"/>
<Label Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding Date}" VerticalOptions="Start"/>
<Label Grid.Row="2" Grid.Column="0" Text="Monto Total:" VerticalOptions="Start"/>
<Label Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding Total, StringFormat='{0:N2}€'}" VerticalOptions="Start"/>
<Label Grid.Row="3" Grid.ColumnSpan="3" Text="Detalle Compra" VerticalOptions="Start"/>
<BoxView Grid.Row="4" Grid.ColumnSpan="3" Color="Gray" HeightRequest="2" HorizontalOptions="Fill" />
<Label Grid.Row="5" Grid.Column="0" Text="Nombre" VerticalOptions="Start" TextColor="#9C2424"/>
<Label Grid.Row="5" Grid.Column="1" Text="Monto" VerticalOptions="Start" TextColor="#9C2424"/>
<Label Grid.Row="5" Grid.Column="2" Text="Cantidad" VerticalOptions="Start" TextColor="#9C2424"/>
<StackLayout Grid.Row="6" Grid.ColumnSpan="3" Margin="0" Padding="0">
<ListView x:Name="ListViewOrders" ItemsSource="{Binding ListOrders}" HasUnevenRows="True" IsPullToRefreshEnabled="False" >
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:CrOrder">
<ViewCell IsEnabled="False">
<Grid RowSpacing="0" ColumnSpacing="0" Margin="0" MinimumHeightRequest="50">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="0" Text="{Binding Reference}" TextColor="Black" VerticalOptions="Center" FontSize="12" />
<Label Grid.Row="0" Grid.Column="1" Text="{Binding Price, StringFormat='{0:N2}€'}" TextColor="Black" VerticalOptions="End" FontSize="12" />
<Label Grid.Row="0" Grid.Column="2" Text="{Binding Quantity}" TextColor="Black" VerticalOptions="End" FontSize="12"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>...
And on my ContentPage I don't have anything
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class InvoicePage : ContentPage
{
public InvoicePage()
{
InitializeComponent();
//BindingContext = new InvoiceViewModel();
}
}
So on my View I have put a label to check what I thought was happening. So the label shows right the total but when I use the ListView binging it doesn't work I don't know why it is null there.
As you can see the label works fine but where it sais "Monto Total" it shows nothing. Please help I don't know what is going on. Thanks.
EDIT
I tried naming the Total property different and then when I add my Invoice entity to my list I do this
Total = Convert.ToDecimal(TotalCart),
But it isn't working eitherway. I don't know why the first time it returns the value fine but the second it doesn't.
After debbuging I have realized when getting the total property that the first time when GetListCart is being called the value is null and the second time, when the label text is set it returns the correct value. Why is this happening?

WPF Xceed Wizard Event in Next button

I'm creating a Wizard to export DB tables into CSV.
I'm using Xceed Wizard and I need an Event in Next button. I want to validate the parameters before going to the next page when I click "Next", but I only can set CanSelectNextPage.
XAML code:
<xctk:WizardPage x:Name="PageBD1" PageType="Interior"
Title="{DynamicResource PageBD1Title}"
Description="{DynamicResource PageBD1Desc}"
NextPage="{Binding ElementName=PageBD2}"
PreviousPage="{Binding ElementName=Page1}"
CanSelectNextPage="False">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="5*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock x:Name="tbBDInfoServer1" Text="{DynamicResource tbBDInfoServer1}" Grid.Row="0" Grid.Column="0" />
<TextBox x:Name="tbBDServer1" Grid.Row="0" Grid.Column="2" TextChanged="tbBD1_TextChanged"/>
<TextBlock x:Name="tbBDInfoName1" Text="{DynamicResource tbBDInfoName1}" Grid.Row="1" Grid.Column="0" Margin="0,10,0,0" />
<TextBox x:Name="tbBDName1" Grid.Row="1" Grid.Column="2" Margin="0,10,0,0" TextChanged="tbBD1_TextChanged"/>
<TextBlock x:Name="tbBDInfoUser1" Text="{DynamicResource tbBDInfoUser1}" Grid.Row="2" Grid.Column="0" Margin="0,10,0,0" />
<TextBox x:Name="tbBDUser1" Grid.Row="2" Grid.Column="2" Margin="0,10,0,0" TextChanged="tbBD1_TextChanged"/>
<TextBlock x:Name="tbBDInfoPwd1" Text="{DynamicResource tbBDInfoPwd1}" Grid.Row="3" Grid.Column="0" Margin="0,10,0,0" />
<PasswordBox x:Name="tbBDPwd1" Grid.Row="3" Grid.Column="2" Margin="0,10,0,0"/>
</Grid>
</xctk:WizardPage>
C# code:
private void tbBD1_TextChanged(object sender, TextChangedEventArgs e)
{
if (tbBDServer1.Text != "" && tbBDName1.Text != "" && tbBDUser1.Text != "")
{
PageBD1.CanSelectNextPage = true;
}
else
PageBD1.CanSelectNextPage = false;
}
Thanks.

CollectionView within a DataTemplate always remains empty

I have a CarouselView in which inside the DataTemplate I have a CollectionView, whose ItemsSource property is binded to an Observablecollection, in which elements are added only when the user presses on a button. The problem is that this CollectionView is always empty, I can't see any items
<CarouselView
x:Name="CollectionDiary"
RelativeLayout.YConstraint="{ConstraintExpression
Type=Constant,
Constant=242}"
RelativeLayout.WidthConstraint="{ConstraintExpression
Type=RelativeToParent,
Property=Width,
Factor=1}"
PeekAreaInsets="20"
HeightRequest="330">
<CarouselView.ItemsLayout>
<LinearItemsLayout Orientation="Horizontal" SnapPointsType="MandatorySingle" SnapPointsAlignment="Center" ItemSpacing="5"/>
</CarouselView.ItemsLayout>
<CarouselView.ItemTemplate>
<DataTemplate>
<yummy:PancakeView CornerRadius="22" BackgroundColor="Transparent">
<yummy:PancakeView.Shadow>
<yummy:DropShadow Color="#000000" Offset="2,2" BlurRadius="5" Opacity="0.8" />
</yummy:PancakeView.Shadow>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="15"/>
<RowDefinition Height="45"/>
<RowDefinition Height="268"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.Background>
<LinearGradientBrush StartPoint="1,0" EndPoint="1,1">
<GradientStop Color="Black" Offset="0" />
<GradientStop Color="#4191cc" Offset="1.0" />
</LinearGradientBrush>
</Grid.Background>
<Label Grid.Row="0" Grid.Column="1" Text="{Binding Data}" FontSize="14" TextColor="Gray" VerticalTextAlignment="End" Margin="10,5,10,0"/>
<Label Grid.Row="1" Grid.Column="1" Text="{Binding Orario}" FontSize="14" TextColor="Gray" VerticalTextAlignment="End" Margin="10,0"/>
<Image Grid.Row="0" Grid.RowSpan="3" Grid.Column="0" Margin="15,15,0,0" Source="{Binding Umore}" HeightRequest="60"/>
<Label Grid.Row="2" Grid.Column="1" Text="{Binding TipoUmore}" FontAttributes="Bold" TextColor="{Binding ColoreUmore}" FontSize="22" Margin="10,0" VerticalOptions="Start"/>
<Label Grid.Row="3" Grid.Column="1" TextColor="White" FontSize="16" Text="{Binding Nota}" Margin="10,0" VerticalOptions="Start" HorizontalTextAlignment="Start"/>
<CollectionView
Grid.Row="2"
Grid.Column="0"
Margin="10"
SelectionMode="None"
ItemsSource="{Binding listEmojiDiarioView}">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" VerticalItemSpacing="10" HorizontalItemSpacing="10"/>
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image Grid.Row="0" Grid.Column="0" Source="{Binding SourceImg}"/>
<Label Grid.Row="0" Grid.Column="1" Text="{Binding id}" TextColor="White" FontSize="13"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Grid>
</yummy:PancakeView>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
c#
ObservableCollection<HumorDiary> listDiario = new ObservableCollection<HumorDiary>();
ObservableCollection<IconDiary> listEmojiDiarioView = new ObservableCollection<IconDiary>();
private async void BTSaveDiary_Clicked(object sender, EventArgs e)
{
HumorDiary hum = new HumorDiary
{
Nota = TestoDiary.Text,
Data = DateTime.Today.Day.ToString() + " " + Mese,
Orario = DateTime.Now.TimeOfDay.ToString().Remove(5,DateTime.Now.TimeOfDay.ToString().Length-5),
Anno = DateTime.Now.Year.ToString(),
Umore = "Smile" + NUmore + ".png",
TipoUmore = tipoUmore,
ColoreUmore = Colore,
IconTot = NIcon,
};
string[] srListIcon = NIcon.Split(new string[] { set.Tag }, StringSplitOptions.RemoveEmptyEntries);
foreach (string sr in srListIcon)
{
string src = sr.Substring(0, 9);
string id = sr.Substring(9, sr.Length-9);
IconDiary ic = new IconDiary
{
SourceImg = src,
id = id,
};
listEmojiDiarioView.Add(ic);
}
listDiario.Insert(0, hum);
CollectionDiary.ItemsSource = listDiario.Take(3);
}
Since the BindingContext inside a CarouselView changes and takes it ItemsSource as a BindingContext, you need to explicitly specify your BindingContext in case of your CollectionView. I guess if you look at the logs you will find some binding error/failure because it was looking for an IEnumerable property with the name of listEmojiDiarioView inside listDiario which obviously is not there.
One way you can overcome this is by using a reference of your page as binding source:
<ContentPage x:Name="pageref" ...
<CollectionView ...
ItemsSource="{Binding Source={x:Reference pageref}, Path=BindingContext.listEmojiDiarioView}">
listEmojiDiarioView must be a property not a field
If it is not working check weather you have implemented the INotifyPropertyChanged on your ObservableCollection used in binding or no.
Omitted code remains unchanged.
Related documentation
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-binding-basics

Bind Combobox in WPF to Entity class

I have a data input form where i have textboxes,comboboxes and datepickers. I want to Bind comboboxes to the DB column so that users select the correct value for insertion. I have attached the viewmodel class and XAML code. In the viewmodel code "private void GetSW()" - this gets all the list of the entity class and "private void addSW()" this adds the record to the DB, Except the combobox binding everything works fine. in XAML i have binded combobox like this but this give blank combobox, please help what i am missing. I researched many topics on this forum but didn't find any solution
<ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding newSW.PreviousSW}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="20"/>
Its a ViewModel Code
using BusinessEntities;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MUDB.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace MUDB.Ui.Logic
{
public class SoftwareVersionListViewModel:ViewModelBase
{
private bool enableRowDetails=false;
public bool EnagleRowDetails
{
get { return enableRowDetails; }
set {
enableRowDetails = value;
RaisePropertyChanged();
}
}
public SoftwareVersionListViewModel()
{
SaveSW = new RelayCommand(addSW);
//savecommand = new RelayCommand(addprod);
GetSW();
newSW = new SoftwareDefEntity();
EditSW = new RelayCommand(() => {
EnagleRowDetails = true;
MessageBox.Show("Edit button clicked!!");});
//SWList = new SoftwareDefEntity(); //Initializing the object of the Entity class
}
public List<SoftwareDefEntity> SWentities
{
get;
set;
}
private SoftwareDefEntity _selectedsw;
public SoftwareDefEntity Selectedsw
{
get { return _selectedsw; }
set
{
_selectedsw = value; //This will get all the values of that particular Selected row that are defined in the entity class
EnagleRowDetails = false; //Reset boolean value EnagleRowDetails, so that the selected rowdetails are disabled until Edit button is not clicked.
//ShowView();
}
}
public RelayCommand SaveSW { get; private set; }
public RelayCommand EditSW { get; private set; }
public SoftwareDefEntity newSW { get; private set; }
private void ShowView()
{
//cUSTOM METHODS
}
private void GetSW() // Method that reads the data from the service layer
{
SWDefService obj = new SWDefService();
SWentities = obj.getSW() ; //getSW is the method refered in Service layer
}
private void addSW()
{
SWDefService obj = new SWDefService();
obj.addSW(newSW); //newproduct object will hold the value of the binded control, in XAML its binded like this "{Binding newproduct.ProductName(ProductName is the field name in the entityclass/DB table)}"
newSW = new SoftwareDefEntity();
}
}
}
This is the XAML Code
<UserControl x:Class="MUDB.Ui.CreateSW"
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:MUDB.Ui"
xmlns:converter="clr-namespace:MUDB.Ui.Logic.Converters;assembly=MUDB.Ui.Logic"
xmlns:enums="clr-namespace:MUDB.Ui.Logic.Enums;assembly=MUDB.Ui.Logic"
mc:Ignorable="d" Height="Auto" Width="Auto"
DataContext="{Binding SoftwareVersionList,Source={StaticResource Locator}}" >
<UserControl.Resources>
<converter:RadioButtonToBooleanConverter x:Key="RadioButtonToBooleanConverter" />
</UserControl.Resources>
<Grid>
<Border Background="#90000000" Visibility="{Binding Visibility}">
<Border BorderBrush="Black" BorderThickness="1" Background="White"
CornerRadius="10,0,10,0" VerticalAlignment="Center"
HorizontalAlignment="Center">
<Border.BitmapEffect>
<DropShadowBitmapEffect Color="Black" Opacity="0.5" Direction="270" ShadowDepth="0.7" />
</Border.BitmapEffect>
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="25"/>
<RowDefinition Height="30"/>
<RowDefinition Height="25"/>
<RowDefinition Height="30"/>
<RowDefinition Height="25"/>
<RowDefinition Height="30"/>
<RowDefinition Height="100"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Label Content="Create New Software Version" Grid.Column="0" Grid.Row="0" Foreground="White" Background="black"
HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.ColumnSpan="3" />
<Label Content="ECU" Grid.Column="0" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Software Name" Grid.Column="1" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Previous Software" Grid.Column="2" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Request Freeze Date" Grid.Column="0" Grid.Row="3" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Request Freeze Status" Grid.Column="1" Grid.Row="3" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Software Freeze Date" Grid.Column="0" Grid.Row="5" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Center" />
<Label Content="Software Freeze Status" Grid.Column="1" Grid.Row="5" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Center" />
<Label Content="Comments" Grid.Column="0" Grid.Row="7" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Center" />
<ComboBox x:Name="ECU" Grid.Column="0" Grid.Row="2" Text="{Binding newSW.ECU}" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="80" Height="Auto">
<ComboBoxItem Name="cbi1">ACM</ComboBoxItem>
<ComboBoxItem Name="cbi2">MCM</ComboBoxItem>
</ComboBox>
<TextBox x:Name="SW" Grid.Column="1" Grid.Row="2" Text="{Binding newSW.SoftwareName}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="Auto" Width="150" />
<ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding PreviousSW}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="20"/>
<DatePicker Grid.Column="0" Grid.Row="4" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="top" SelectedDate="{Binding newSW.Req_Freeze_Date}" Height="Auto" Width="Auto"/>
<DatePicker Grid.Column="0" Grid.Row="6" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="top" SelectedDate="{Binding newSW.SW_Freeze_Date}" Height="Auto" Width="Auto"/>
<RadioButton Content="Yes" GroupName="ReQstat" IsChecked="{Binding newSW.Req_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.Yes}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="4" HorizontalAlignment="Left" VerticalAlignment="Top" Height="14" Width="Auto"/>
<RadioButton Content="No" GroupName="ReQstat" IsChecked="{Binding newSW.Req_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.No}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="4" Margin="60 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="Auto" Width="Auto"/>
<RadioButton Content="Yes" GroupName="SWstat" IsChecked="{Binding newSW.SW_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.Yes}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="6" HorizontalAlignment="Left" VerticalAlignment="Top" Height="Auto" Width="Auto"/>
<RadioButton Content="No" GroupName="SWstat" IsChecked="{Binding newSW.SW_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.No}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="6" Margin="60 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="Auto" Width="Auto"/>
<TextBox x:Name="CommenttextBox" Grid.Column="1" Grid.Row="7" HorizontalAlignment="Left" Height="69" TextWrapping="WrapWithOverflow" VerticalAlignment="Center" Text="{Binding Comment}" Width="170" Margin="4.4,2.2,0,0" />
<UniformGrid Grid.Row="9" Margin="2" Columns="2" HorizontalAlignment="Stretch"
VerticalAlignment="Center" Height="Auto">
<Button x:Name="SaveButton" Command="{Binding SaveSW}" Content="Save" Height="27" />
<Button x:Name="CloseButton" Click="CloseButton_Click" Content="Close" Height="26" />
</UniformGrid>
</Grid>
</Border>
</Border>
</Grid>
</UserControl>
I guess you want to display the list of SoftwareDefEntity objects in your ComboBox.
Bind to the SWentities property then:
<ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding SWentities}" DisplayMemberPath="Name" ... />
And raise the PropertyChanged event in its setter of this property:
private List<SoftwareDefEntity> _swEntities;
public List<SoftwareDefEntity> SWentities
{
get { return _swEntities; }
set { _swEntities = value; RaisePropertyChanged(); }
}
This is the code to bind the data to combobox. i did not add any of other controls since those are working fine at your place. Observable collection is easy way to bind combobox .
Here is your View Model..
public class SoftwareVersionListViewModel : ViewModelBase
{
public SoftwareVersionListViewModel()
{
GetSW();
}
//Define the observable collection
private ObservableCollection<SoftwareDefEntity> _SWmappings2 = new ObservableCollection<SoftwareDefEntity>();
//here is your Entity list
public List<SoftwareDefEntity> SWentities
{
get;
set;
}
// Obeservable collection property for access
public ObservableCollection<SoftwareDefEntity> SWmappings2
{
get { return _SWmappings2; }
set
{
_SWmappings2 = value;
OnPropertyChanged("appeventmappings2");
}
}
/// <summary>
/// load the combobox
/// </summary>
private void GetSW() // Method that reads the data from the service layer
{
SWDefService obj = new SWDefService();
SWentities = obj.getSW(); //getSW is the method refered in Service layer
SWentities.ForEach(_SWmappings2.Add);
}
}
and Xaml...
<ComboBox x:Name="ComboBox" ItemsSource="{Binding SWmappings2, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="PreviousSW" SelectedItem="{Binding PreviousSW, Mode=TwoWay}" Grid.Row="0" >
</ComboBox>

Categories