I am trying to select multiple options from a listbox. I even tried using Multiple Selection mode but it doesnot work for this specific listbox but works for others. ListBox name is listBox. I am adding the data to that list dynamically in OrderWindow class and i have implemented the selection_changed method but i am unable to select multiple items and i have also binded a list to this listbox.
Here is the code:
namespace ACW2
{
/// <summary>
/// Interaction logic for OrderWindow.xaml
/// </summary>
public partial class OrderWindow : Window
{
List<MenuClass> PizzaInStock = new List<MenuClass>();
List<InvClass> inventory = MainWindow.ItemList;
List<InvClass> pizzatoppings = new List<InvClass>();
List<String> Mainlist = new List<String>();
String addpizzas = "";
double pizzaprice = 0;
private void extratoppingslist(String name)
{
pizzatoppings = new List<InvClass>();
var pizza = MainWindow.MenuList.FirstOrDefault(x => x.Name == name);
List<Ingredient> originaltoppings = pizza.Ingredients;
int originaltoppingsize = pizza.Ingredients.Count;
if (originaltoppingsize >= 5)
{
return;
}
var allpizzatoppings = from a in inventory
where a.Category == "pizza"
select a;
foreach (InvClass item in allpizzatoppings)
{
int exists = 0;
if (originaltoppingsize == 5)
{
break;
}
foreach(Ingredient ing in originaltoppings)
{
if (item.Name.Equals(ing.Name))
{
exists = 1;
break;
}
}
if (exists == 0)
{
pizzatoppings.Add(item);
}
++originaltoppingsize;
}
listBox.ItemsSource = null;
listBox.ItemsSource = pizzatoppings;
}
private void updatepizzaprice()
{
pizzaprice = 0;
if (comboBox1.SelectedItem != null&& comboBox.SelectedItem != null)
{
String pizza = comboBox.SelectedItem.ToString();
String size = comboBox1.SelectedItem.ToString();
extratoppingslist(pizza);
var iteminlists = MainWindow.MenuList.FirstOrDefault(x => (x.Name == pizza) && (x.Size == size));
pizzaprice += (Convert.ToDouble(iteminlists.Price));
List<Ingredient> list = iteminlists.Ingredients;
if (checkBox.IsChecked == true)
{
foreach(Ingredient iss in list)
{
Trace.WriteLine(iss.Name);
}
var item = list.FirstOrDefault(x => x.Name == " dough");
var ingr= inventory.FirstOrDefault(x => x.Name == " dough");
pizzaprice += ((Convert.ToDouble(item.Quantity) * 0.1))*ingr.Price;
var items = list.FirstOrDefault(x => x.Name == " mozzarella");
var ingrs = inventory.FirstOrDefault(x => x.Name == " mozzarella");
pizzaprice += ((Convert.ToDouble(items.Quantity) * 0.15)) * ingrs.Price;
}
List<InvClass> toppings = listBox.SelectedItems.Cast<InvClass>().ToList();
foreach (InvClass top in toppings)
{
var item = inventory.FirstOrDefault(x => x.Name == top.Name);
Trace.WriteLine(top.Name);
if (iteminlists.Size == " regular")
{
pizzaprice += item.Price * 0.25;
}
else if (iteminlists.Size == " large")
{
pizzaprice += item.Price * 0.35;
}
else if (iteminlists.Size == " extra-large")
{
pizzaprice += item.Price * 0.75;
}
}
textBox.Text = "£ " + pizzaprice.ToString();
}
}
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
updatepizzaprice();
}
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
updatepizzaprice();
}
private void checkBox_Checked(object sender, RoutedEventArgs e)
{
updatepizzaprice();
}
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
updatepizzaprice();
}
private void checkBox_unchecked(object sender, RoutedEventArgs e)
{
updatepizzaprice();
}
private void checkbox1_unchecked(object sender, RoutedEventArgs e)
{
updateburgerprice();
}
private void checkbox2_unchecked(object sender, RoutedEventArgs e)
{
updateburgerprice();
}
}
}
Here is the xml code:
<Window x:Class="ACW2.OrderWindow"
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:local="clr-namespace:ACW2"
mc:Ignorable="d"
Title="OrderWindow" SizeToContent="WidthAndHeight">
<StackPanel Orientation="Vertical">
<Label x:Name="label10" Content="Create Order" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top" FontSize="24"/>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<Label x:Name="label4_Copy" Content="Order Summary" Margin="5" FontSize="16"/>
<ListBox x:Name="listBox2" Height="160" Margin="5" MinWidth="180"/>
<Button x:Name="button4" Content="Remove Item" Margin="5" Width="75"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label13" Content="Ingredient Cost (£)" Margin="5" VerticalAlignment="Top"/>
<TextBox x:Name="textBox4" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label12" Content="Net Profit (£)" Margin="5"/>
<TextBox x:Name="textBox5" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label11" Content="Total Price(£)" Margin="5"/>
<TextBox x:Name="textBox1" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<Button x:Name="button3" Content="Complete Order" Margin="5"/>
</StackPanel>
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<Label x:Name="label4" Content="1. Pizzas" Margin="5" FontSize="16"/>
<Border BorderBrush="Gray" BorderThickness="1" Margin="5">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label1" Content="Pizza" Margin="5" />
<ComboBox x:Name="comboBox" Margin="5" Width="120" SelectionChanged="comboBox_SelectionChanged"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label" Content="Size" Margin="5"/>
<ComboBox x:Name="comboBox1" Margin="5" Width="120" SelectionChanged="comboBox1_SelectionChanged"/>
</StackPanel>
<CheckBox x:Name="checkBox" Content="Stuffed Crust" Margin="5" HorizontalAlignment="Center" Checked="checkBox_Checked" Unchecked="checkBox_unchecked"/>
<Label x:Name="label14" Content="Extra Toppings" Margin="5,5,5,0" HorizontalAlignment="Center"/>
<ListBox x:Name="listBox" Height="120" Margin="5,0,5,5" MinWidth="140" HorizontalAlignment="Center" SelectionChanged="listBox_SelectionChanged" SelectionMode="Multiple">
<ListBox.ItemTemplate>
<DataTemplate x:Name="Lists">
<TextBlock>
<Run Text="{Binding Name}"/>
<Run Text=" , "/>
<Run Text="{Binding Price}"/>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label9" Content="Price (£)" Margin="5"/>
<TextBox x:Name="textBox" Height="24" Margin="5" TextWrapping="Wrap" Text="£" VerticalAlignment="Top" Width="80"/>
</StackPanel>
<Button x:Name="button" Content="Add to Order" Margin="5" Width="80" HorizontalAlignment="Right"/>
</StackPanel>
</Border>
</StackPanel>
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<Label x:Name="label5" Content="2. Burgers" Margin="5" FontSize="16"/>
<Border BorderBrush="Gray" BorderThickness="1" Margin="5">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label2" Content="Burger" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top"/>
<ComboBox x:Name="comboBox2" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top" Width="107" SelectionChanged="comboBox2_SelectionChanged"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label3" Content="Size" Margin="5" VerticalAlignment="Center"/>
<RadioButton x:Name="radioButton" Content="1/4lb" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" Checked="radioButton_Checked"/>
<RadioButton x:Name="radioButton1" Content="1/2lb" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" Checked="radioButton1_Checked"/>
</StackPanel>
<StackPanel Orientation="Vertical" HorizontalAlignment="Center">
<CheckBox x:Name="checkBox1" Content="Salad" Margin="2" Checked="checkBox1_Checked" Unchecked="checkbox1_unchecked"/>
<CheckBox x:Name="checkBox2" Content="Cheese" Margin="2" Checked="checkBox2_Checked" Unchecked="checkbox2_unchecked"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label8" Content="Price (£)" HorizontalAlignment="Left" Margin="5" />
<TextBox x:Name="textBox2" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<Button x:Name="button1" Content="Add to Order" Margin="5" Width="80" HorizontalAlignment="Right" Click="button1_Click"/>
</StackPanel>
</Border>
</StackPanel>
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<Label x:Name="label6" Content="3. Sundries" Margin="5" FontSize="16"/>
<Border BorderBrush="Gray" BorderThickness="1" Margin="5">
<StackPanel Orientation="Vertical">
<ListBox x:Name="listBox1" Height="120" MinWidth="140" Margin="5" SelectionChanged="listBox1_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate x:Name="Lists11">
<TextBlock Background="{Binding Color}">
<Run Text="{Binding Name}"/>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Orientation="Horizontal">
<Label x:Name="label7" Content="Price (£)" Margin="5" VerticalAlignment="Top"/>
<TextBox x:Name="textBox3" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<Button x:Name="button2" Content="Add to Order" HorizontalAlignment="Right" Margin="5" Width="80" Click="button2_Click"/>
</StackPanel>
</Border>
</StackPanel>
</StackPanel>
</StackPanel>
</Window>
I am creating windows phone 8 application, I have checkbox inside listbox, how do I get checkbox "CHECKED" when I click on checkbox?
I tried my best but not getting the result?
see my code below:
<ListBox x:Name="listBox1" Width="429" Height="621" HorizontalAlignment="Left" Margin="21,43,0,59" VerticalAlignment="Top" ItemsSource="{Binding}" SelectedItem="{Binding}" SelectionChanged="listBox1_SelectionChanged" SelectionMode="Extended">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<StackPanel Orientation="Vertical" Width="440">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" TextWrapping="Wrap" Foreground="Black" FontSize="22" Height="30" TextAlignment="Left" Width="Auto" FontWeight="SemiBold"/>
<TextBlock Text="{Binding}" TextWrapping="Wrap" Foreground="Black" FontSize="22" Margin="5" Height="30" TextAlignment="Left" Width="Auto" FontWeight="SemiBold"/>
</StackPanel>
<StackPanel>
<TextBlock Text="Favorite" TextWrapping="Wrap" Foreground="Black" FontSize="22" Height="30" FontWeight="SemiBold" Margin="344,-35,9,0"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" TextWrapping="Wrap" Foreground="Black" FontSize="22" Height="Auto" Width="Auto" TextAlignment="Left" FontWeight="SemiBold"/>
</StackPanel>
<CheckBox x:Name="CheckBox1" Height="72" Foreground="Black" IsChecked="False" Margin="353,-40,28,0" BorderBrush="Black" Loaded="CheckBox1_Loaded" Checked="CheckBox1_Checked" Unchecked="CheckBox1_Unchecked"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here is my code behind file:
private void CheckBox1_Checked(object sender, RoutedEventArgs e)
{
CheckBox cb = (CheckBox)sender;
cb.IsChecked = true;
}
I tried this on emulator in my listbox and it works fine. The textboxes checked and unchecked without any problem.
<ListBox.BorderBrush>
<SolidColorBrush />
</ListBox.BorderBrush>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="0,1,0,0" Width="600" Padding="0">
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<Image Stretch="UniformToFill" Source="{Binding Image}" Width="130" Height="130" HorizontalAlignment="Center" VerticalAlignment="Center">
<Image.Clip>
<RectangleGeometry RadiusX="15" RadiusY="15" Rect="0,0,130,130" />
</Image.Clip>
</Image>
<--CheckBox x:Name="CheckBox1" Height="72" Foreground="Black" IsChecked="False" BorderBrush="Black"/-->
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I got the solution:
private void CheckBox1_Checked(object sender, RoutedEventArgs e)
{
CONTACTS data = (sender as CheckBox).DataContext as CONTACTS;
string contactId = data.contactId;
string isFav = data.isFavourite.ToString();
}
Here is the answer:
private void CheckBox1_Checked(object sender, RoutedEventArgs e)
{
CLASS_NAME item = (sender as CheckBox).DataContext as CLASS_NAME;
string id = item.Id;
string name = item.Name;
}
I have longListSelector:
<DataTemplate x:Key="AddrBookItemTemplate" >
<StackPanel VerticalAlignment="Top">
<Grid Background="#3FCDCDCD" Margin="3,3,3,3">
<Image Source ="{Binding UrlImage}" Height="100" Width="100" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,0,0,0" Stretch="Fill"/>
<TextBlock Text="{Binding Title}" TextWrapping="Wrap" Margin="110,0,0,0" Foreground="Black" FontFamily="Portable User Interface"/>
</Grid>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<phone:LongListSelector
x:Name="AddrBook"
Background="Transparent"
ItemTemplate="{StaticResource AddrBookItemTemplate}"
IsGroupingEnabled="true"
HideEmptyGroups ="true"
SelectionChanged="AddrBook_SelectionChanged"
/>
Preview - name of my class
How can i get index of PressedItem?
What should i write here -
private void AddrBook_SelectionChanged(object sender, SelectionChangedEventArgs e)
{ }
you should write
var longlistselector = (sender as LongListSelector);
int index = longlistselector.DataSource.IndexOf(longlistselector.SelectedItem);
I have a LongListSelector, that store data from my Azure SQL Database.
This is my C# code:
private async void RefreshTodoItemsToday()
{
try
{
coll = await todoTable
.Where(todoItem => todoItem.TpEvt == "today")
.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException e)
{
MessageBox.Show(e.Message, "Error loading items", MessageBoxButton.OK);
}
ListItemstoday.ItemsSource = coll;
}
And this is my XAML:
<phone:LongListSelector Name="ListItemsToday">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="TxtEvt" Text="{Binding Text}" TextWrapping="Wrap" Foreground="Gray" TextAlignment="Center" FontSize="30" Padding="30">
</TextBlock>
<Line X1="0" Y1="10" X2="240" Y2="10" Stroke="SkyBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Height="21"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
The registers are stored in my LongListSelector - it is working fine.
Now this is my doubt: How can i read the properties for each register in my LongListSelector? For each register, i have fields such as "Id", "TypeEvent", "Hour", "Date", etc.
So, how can i read each individual value, according by the SelectedItem in LongListSelector?
For example, if i wish to see in a MessageBox the ID from a Selected Item...how can i do this in code?
I tried the following:
var tmp1 = (TodoItem)ListItemsToday.SelectedItem;
var tmp2 = tmp1.Id;
MessageBox.Show(tmp2.ToString());
When i try to cast this code, this is the error i got:
*System.NullReferenceException: Object reference not set to an instance of an object.
at Project.MainPage.ContextMenuRemove_Click(Object sender, EventArgs e)*
Someone can help'me, please?
Thank you friends.
React to selection changed:
<phone:LongListSelector Name="ListItemsToday" SelectionChanged="ListItemsToday_SelectionChanged">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Name="TxtEvt" Text="{Binding Text}" TextWrapping="Wrap" Foreground="Gray" TextAlignment="Center" FontSize="30" Padding="30">
</TextBlock>
<Line X1="0" Y1="10" X2="240" Y2="10" Stroke="SkyBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Height="21"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
with this
private void ListItemsToday_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = ListItemsToday.SelectedItem as TodoItem;
MessageBox.Show(item.Text);
}
Or react to tap event in data template
<phone:LongListSelector Name="ListItemsToday" >
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Tap="ListItemsToday_Tap">
<TextBlock Name="TxtEvt" Text="{Binding Text}" TextWrapping="Wrap" Foreground="Gray" TextAlignment="Center" FontSize="30" Padding="30">
</TextBlock>
<Line X1="0" Y1="10" X2="240" Y2="10" Stroke="SkyBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Height="21"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
like this:
private void ListItemsToday_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var item = (sender as FrameworkElement).DataContext as TodoItem;
MessageBox.Show(item.Text);
}
I'm create an module which is a Editing Bill module which will enable the user to edit the available in the database. I'm facing one validation problem which is that when the user don't want to edit the bill & click on the "Cancel" button will back to the listview to continue select another record. Here is my problem come as when the user didn't make any modification & accidentally click on the "Status" combo from "UNPAID" to "PAID" then directly quite. When re select the record then the record status value will become "PAID" instead of "UNPAID" which is the actual value.
How can I do so that when every time the user don't make any modification & return back to the listview will set back the default value for the combobox.
Thank you all for viewing this question & hope to receive reply :)
I will attach my code so that easily to refer:
XAML File
<Window x:Class="HouseWivesSavior.HomecareModule.EditBillRemainder"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="EditBillRemainder" Height="600" Width="800" Loaded="Window_Loaded">
<Window.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFFFFFFF" Offset="0"/>
<GradientStop Color="#FFFF00FF" Offset="1"/>
</LinearGradientBrush>
</Window.Background>
<Window.Resources>
<DataTemplate x:Key="MyDataTemplate">
<Border BorderBrush="#FF000000" BorderThickness="1,1,0,1" Margin="-6,-2,-6,-2">
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Path=BillName}"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="MyDataTemplate2">
<Border BorderBrush="#FF000000" BorderThickness="1,1,0,1" Margin="-6,-2,-6,-2">
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Path=BillDescription}"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="MyDataTemplate3">
<Border BorderBrush="#FF000000" BorderThickness="1,1,0,1" Margin="-6,-2,-6,-2">
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Path=BillAmount}"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="MyDataTemplate4">
<Border BorderBrush="#FF000000" BorderThickness="1,1,1,1" Margin="-6,-2,-6,-2">
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Path=BillDueDate, StringFormat='dd-MM-yyyy'}"/>
</StackPanel>
</Border>
</DataTemplate>
<Style x:Key="MyItemContainerStyle" TargetType="{x:Type ListViewItem}">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Stretch" />
<!--<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" />-->
</Style>
<!--DatePickerTextBoxFormat-->
<Style TargetType="{x:Type DatePickerTextBox}">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<TextBox x:Name="PART_TextBox" Text="{Binding Path=SelectedDate, StringFormat='dd-MM-yyyy', RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<ListView Name="lvwBooks" Background="White" ItemsSource="{Binding}" Margin="131,130,4,6" ItemContainerStyle="{DynamicResource MyItemContainerStyle}">
<ListView.View>
<GridView>
<GridViewColumn Header="Bill Name" Width="100" CellTemplate="{DynamicResource MyDataTemplate}"/>
<GridViewColumn Header="Description" Width="250" CellTemplate="{DynamicResource MyDataTemplate2}"/>
<GridViewColumn Header="Amount" Width="160" CellTemplate="{DynamicResource MyDataTemplate3}"/>
<GridViewColumn Header="Due Date" Width="100" CellTemplate="{DynamicResource MyDataTemplate4}"/>
<GridViewColumn Header="Edit">
<GridViewColumn.CellTemplate>
<DataTemplate>
<UserControl>
<Hyperlink Click="InputBox_Click">Edit
<Hyperlink.Style>
<Style TargetType="{x:Type Hyperlink}">
<Setter Property="Hyperlink.IsEnabled" Value="False" />
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}, Path=IsSelected}" Value="True">
<Setter Property="Hyperlink.IsEnabled" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</Hyperlink.Style>
</Hyperlink>
</UserControl>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<!-- It's important that this is in the end of the XAML as it needs to be on top of everything else! -->
<Grid x:Name="InputBox" Visibility="Collapsed">
<Grid Background="Black" Opacity="0.5" />
<Border
MinWidth="250"
Background="Orange"
BorderBrush="Black"
BorderThickness="1"
CornerRadius="0,40,0,40"
HorizontalAlignment="Center"
VerticalAlignment="Center" Height="493" Margin="130,30,120,38" Width="528">
<Canvas Height="446" Width="524">
<GroupBox Header="General Information" Height="141" HorizontalAlignment="Left" Margin="193,52,0,0" Name="groupBox1" VerticalAlignment="Top" Width="495" Canvas.Left="-173" Canvas.Top="-67">
<Canvas Background="WhiteSmoke" Opacity="1">
<GridSplitter Background="#FFBCBCBC" HorizontalAlignment="Left" Margin="207,13,0,140" ResizeBehavior="PreviousAndNext" Width="2" Height="50" Canvas.Left="-3" Canvas.Top="48" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="6,6,0,0" Name="textBlock1" Text="Bill Name" VerticalAlignment="Top" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="215,65,0,0" Name="textBlock4" Text="Due Date" VerticalAlignment="Top" Grid.ColumnSpan="2" />
<GridSplitter HorizontalAlignment="Left" ResizeBehavior="PreviousAndNext"
Width="1" Background="#FFBCBCBC" Margin="206,63,0,9" />
<DatePicker Height="25" HorizontalAlignment="Right" Margin="0,80,157,0" Name="BillDueDatedatePicker" VerticalAlignment="Top" Width="115" Grid.ColumnSpan="2" Canvas.Left="215" Canvas.Top="6" Text="{Binding Path=BillDueDate, StringFormat='dd-MM-yyyy'}" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" SelectedDateFormat="Short"/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="7,29,0,0" Name="BillNameTxtBox" VerticalAlignment="Top" Width="458" Grid.ColumnSpan="2" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" Text="{Binding Path=BillName}"/>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="7,63,0,0" Name="textBlock8" Text="Bill Type" VerticalAlignment="Top" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="8,81,0,0" Name="BillTypeCboBox" VerticalAlignment="Top" Width="193" Canvas.Left="-5" Canvas.Top="8" Text="{Binding Path=BillTypes}" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}">
<ComboBoxItem Content="Water" />
<ComboBoxItem Content="Electricity" />
<ComboBoxItem Content="Gas" />
<ComboBoxItem Content="Internet/broadband"/>
<ComboBoxItem Content="Others"/>
</ComboBox>
<TextBox Canvas.Left="62" Canvas.Top="3" Height="23" Name="textBox1" Width="120" Visibility="Visible" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" Text="{Binding Path=BillNo}"/>
</Canvas>
</GroupBox>
<GroupBox Header="Payment Information" Height="339" HorizontalAlignment="Left" Margin="193,202,0,0" Name="groupBox2" VerticalAlignment="Top" Width="495" Canvas.Left="-174" Canvas.Top="-81">
<Canvas Background="WhiteSmoke" Height="303" Visibility="Visible">
<TextBlock Height="23" HorizontalAlignment="Left" Margin="7,17,0,0" Name="textBlock6" Text="Amount Due" VerticalAlignment="Top" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="7,75,0,0" Name="textBlock7" Text="Description" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="81,14,0,0" Name="BillAmountTxtBox" VerticalAlignment="Top" Width="120" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" Text="{Binding Path=BillAmount}"/>
<TextBox Height="148" HorizontalAlignment="Left" Margin="4,96,0,0" Name="BillDescriptionTxtBox" VerticalAlignment="Top" Width="471" VerticalScrollBarVisibility="Visible" SpellCheck.IsEnabled="True" TextWrapping="Wrap" AcceptsReturn="True" Text="{Binding Path=BillDescription}" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}"/>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="6,46,0,0" Name="textBlock9" Text="Status" VerticalAlignment="Top" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="81,46,0,0" Name="BillStatusCboBox" VerticalAlignment="Top" Width="120" SelectionChanged="comboBox3_SelectionChanged" Text="{Binding Path=BillStatus}" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" >
<ComboBoxItem Content="UNPAID" />
<ComboBoxItem Content="PAID" />
</ComboBox>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="215,14,0,0" Name="textBlock10" Text="Bill is Paid:" VerticalAlignment="Top" />
<DatePicker Text="{Binding Path=BillPaidDate}" Height="25" HorizontalAlignment="Left" Margin="212,37,0,0" Name="BillPaidDatedatePicker" VerticalAlignment="Top" Width="115" IsEnabled="false" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}"/>
<GridSplitter Background="#FFBCBCBC" HorizontalAlignment="Left" Margin="205,14,0,228" ResizeBehavior="PreviousAndNext" Width="2" />
<Separator Height="26" HorizontalAlignment="Left" Margin="7,250,0,0" Name="separator1" VerticalAlignment="Top" Width="470" />
<Button Content="Done" Height="23" HorizontalAlignment="Left" Margin="322,267,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="YesButton_Click" />
<Button Content="Cancel" Height="23" HorizontalAlignment="Left" Margin="402,266,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="NoButton_Click" />
<GridSplitter Background="#FFBCBCBC" HorizontalAlignment="Left" Margin="207,13,0,140" ResizeBehavior="PreviousAndNext" Width="0" />
</Canvas>
</GroupBox>
</Canvas>
</Border>
</Grid>
</Grid>
</Window>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Shapes;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace HouseWivesSavior.HomecareModule
{
/// <summary>
/// Interaction logic for EditBillRemainder.xaml
/// </summary>
public partial class EditBillRemainder : Window
{
public EditBillRemainder()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ShowData();
}
private void InputBox_Click(object sender, RoutedEventArgs e)
{
// CoolButton Clicked! Let's show our InputBox.
InputBox.Visibility = System.Windows.Visibility.Visible;
}
private void NoButton_Click(object sender, RoutedEventArgs e)
{
//ShowData();
// NoButton Clicked! Let's hide our InputBox.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
}
private void ListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var item = sender as ListViewItem;
if (item != null && item.IsSelected)
{
}
}
//Design
private void comboBox3_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
////The logic for this will be stanger but in order to cope iwht the SelectionChange behavior.
//string s1 = BillStatusCboBox.SelectionBoxItem.ToString();
//// MessageBox.Show(s1);
//if (s1.Equals("UNPAID"))
//{
// BillPaidDatedatePicker.IsEnabled = true;
// BillPaidDatedatePicker.Text = DateTime.Now.ToString("d/MM/yyyy");
//}
//if (s1.Equals("PAID"))
//{
// BillPaidDatedatePicker.IsEnabled = false;
// //BillStatusCboBox.SelectedIndex = 0;
//}
ComboBoxItem currentItem = ((System.Windows.Controls.ComboBoxItem)BillStatusCboBox.SelectedItem);
if (currentItem.Content.Equals("PAID"))
{
BillPaidDatedatePicker.IsEnabled = true;
// BuilderupdateButton.Visibility = Visibility.Visible;
}
else {
BillPaidDatedatePicker.IsEnabled = false;
}
}
//Database
public void ShowData()
{
SqlConnection conn;
string connStr = ConfigurationManager.ConnectionStrings["house"].ConnectionString;
conn = new SqlConnection(connStr);
//SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
conn.Open();
SqlCommand comm = new SqlCommand("Select * from bill ORDER BY BillDueDate", conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dt);
lvwBooks.DataContext = dt.DefaultView;
}
private void YesButton_Click(object sender, RoutedEventArgs e)
{
Update();
// YesButton Clicked! Let's hide our InputBox and handle the input text.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
}
public void Update() {
SqlConnection conn;
SqlCommand cmdInsert;
String strUpdate;
string connStr = ConfigurationManager.ConnectionStrings["house"].ConnectionString;
conn = new SqlConnection(connStr);
strUpdate = "UPDATE bill SET BillName=#BillName, BillTypes=#BillTypes, BillDueDate=#BillDueDate, BillAmount=#BillAmount, BillStatus=#BillStatus, BillPaidDate=#BillPaidDate, BillDescription=#BillDescription WHERE BillNo='" + textBox1.Text + "' ";
cmdInsert = new SqlCommand(strUpdate, conn);
cmdInsert.Parameters.AddWithValue("#BillName", BillNameTxtBox.Text);
cmdInsert.Parameters.AddWithValue("#BillTypes", BillTypeCboBox.Text);
cmdInsert.Parameters.AddWithValue("#BillDueDate", DateTime.Parse(BillDueDatedatePicker.Text));
cmdInsert.Parameters.AddWithValue("#BillAmount", BillAmountTxtBox.Text);
cmdInsert.Parameters.AddWithValue("#BillStatus", BillStatusCboBox.Text);
//MessageBox.Show(BillPaidDatedatePicker.Text);
if (BillPaidDatedatePicker.Text.Equals(""))
{
cmdInsert.Parameters.AddWithValue("#BillPaidDate", "");
}
else {
cmdInsert.Parameters.AddWithValue("#BillPaidDate", DateTime.Parse(BillPaidDatedatePicker.Text));
}
// cmdInsert.Parameters.AddWithValue("#BillPaidDate", DateTime.Parse(empty));
cmdInsert.Parameters.AddWithValue("#BillDescription", BillDescriptionTxtBox.Text);
try
{
conn.Open();
int result = cmdInsert.ExecuteNonQuery();
if (result == 1)
{
MessageBox.Show("Bill Edited!!!");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally {
conn.Close();
}
}
}
}
For this case it would be better to user IDataErrorInfo interface instead of using ValiationRule since IDataErrorInfo will be handled inside ViewModel where you also have all the necessary database statements.
Here is a link to a tutorial explaining how to do validation with IDataErrorInfo.
http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/
Have fun :)
I solved it by like this:
Code-Behind:
The problem that I faced is NullReferenceException then I used a try..catch to catch the "NullReferenceException"
private void comboBox3_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem currentItem = ((System.Windows.Controls.ComboBoxItem)BillStatusCboBox.SelectedItem);
try
{
if (currentItem.Content.Equals("PAID"))
{
BillPaidDatedatePicker.IsEnabled = true;
// BuilderupdateButton.Visibility = Visibility.Visible;
}
else
{
BillPaidDatedatePicker.IsEnabled = false;
}
}
catch (NullReferenceException ex){ // At here which you can see.
//I purposely set it to do nothing when catch it.
}
Then when the user accidentally click on the "UPAID" to "PAID" & directly click on the cancel button will invoke "NoButton_Click" which will try to reload & select the value from the database:
private void NoButton_Click(object sender, RoutedEventArgs e)
{
ShowData(); // Invoke & select from database again.
// NoButton Clicked! Let's hide our InputBox.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
}
I know by this way solving my problem will be quite inefficient but get the job done :) Which is fine to me.