Rows do not appear in SQL Server CE WP7 - c#

ToDoDataContext
Here I create a context for database.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Data.Linq;
namespace My_CookBook
{
public class ToDoDataContext : DataContext
{
public static string DBConnectionString = "Data Source=isostore:/kupa.sdf";
public ToDoDataContext(string connectionString)
: base(connectionString)
{ }
public Table<ToDoItem> ToDoItems;
}
}
ToDoItem
Here is model of item.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Data.Linq.Mapping;
namespace My_CookBook
{
[Table]
public class ToDoItem : INotifyPropertyChanged, INotifyPropertyChanging
{
// Define ID: private field, public property and database column.
private int _toDoItemId;
[Column(IsPrimaryKey=true, IsDbGenerated=true,DbType = "INT NOT NULL Identity", CanBeNull=false, AutoSync= AutoSync.OnInsert)]
public int ToDoItemId
{
get
{
return _toDoItemId;
}
set
{
if (_toDoItemId != value)
{
NotifyPropertyChanging("ToDoItemId");
_toDoItemId = value;
NotifyPropertyChanged("ToDoItemId");
}
}
}
/////////////////////////////////////// Nazwa //////////////////////////////////////////
private string _Name;
[Column]
public string Name
{
get
{
return _Name;
}
set
{
if (_Name != value)
{
NotifyPropertyChanging("Name");
_Name = value;
NotifyPropertyChanged("Name");
}
}
}
/////////////////////////////////////// Autor //////////////////////////////////////////
private string _Autor;
[Column]
public string Autor
{
get
{
return _Autor;
}
set
{
if (_Autor != value)
{
NotifyPropertyChanging("Autor");
_Autor = value;
NotifyPropertyChanged("Autor");
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify the page that a data context property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region INotifyPropertyChanging Members
public event PropertyChangingEventHandler PropertyChanging;
// Used to notify the data context that a data context property is about to change
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
#endregion
}
}
Show all
On this page should be display rows.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace My_CookBook
{
public partial class show_all : PhoneApplicationPage
{
// Data context for the local database
private ToDoDataContext toDoDB;
// Define an observable collection property that controls can bind to.
private ObservableCollection<ToDoItem> _toDoItems;
public ObservableCollection<ToDoItem> ToDoItems
{
get
{
return _toDoItems;
}
set
{
if (_toDoItems != value)
{
_toDoItems = value;
NotifyPropertyChanged("ToDoItems");
}
}
}
// Constructor
public show_all()
{
InitializeComponent();
// Connect to the database and instantiate data context.
toDoDB = new ToDoDataContext(ToDoDataContext.DBConnectionString);
// Define the query to gather all of the to-do items.
var toDoItemsInDB = from ToDoItem todo in toDoDB.ToDoItems
select todo;
// Execute the query and place the results into a collection.
ToDoItems = new ObservableCollection<ToDoItem>(toDoItemsInDB);
toDoDB.SubmitChanges();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify the page that a data context property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
Show All xaml
I use binding to retrieve rows.
<Grid x:Name="ContentPanel1" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ListBox x:Name="toDoItemsListBox" ItemsSource="{Binding ToDoItems}"
Grid.Row="0" Margin="12, 0, 12, 0" Width="440">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" Width="440">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<TextBlock
Text="{Binding Path=Name}"
FontSize="{StaticResource PhoneFontSizeLarge}"
Grid.Column="1"
VerticalAlignment="Center"/>
<Button
Grid.Column="2"
x:Name="deleteTaskButton"
BorderThickness="0"
Margin="0">
<Image Source="Images/appbar.delete.rest.png"/>
</Button>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Add New
Here I add new row to the database:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace My_CookBook
{
public partial class add_new : PhoneApplicationPage
{
// Constructor
public add_new()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (slider1 != null)
{
slider1.Value = Math.Round(e.NewValue);
qwe((int)slider1.Value);
}
}
private void qwe(int a)
{
stackPanel1.Height = 1250 + a * 159;
stackPanel2.Height = a * 159;
}
private void button3_Click(object sender, RoutedEventArgs e)
{
CameraCaptureTask camera = new CameraCaptureTask();
camera.Show();
ManipulationCompletedEventArgs photo = new ManipulationCompletedEventArgs();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
ToDoDataContext toDoDB = new ToDoDataContext(ToDoDataContext.DBConnectionString);
ToDoItem newToDo = new ToDoItem();
newToDo.Name = textBox1.Text;
newToDo.Autor = textBox2.Text;
toDoDB.ToDoItems.InsertOnSubmit(newToDo);
toDoDB.SubmitChanges();
MessageBox.Show("Pomyślnie dodano przepis.");
this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify the page that a data context property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
My problem is this, the program does not display any rows (in Show all page) from the database. Why?
In debugger is ok. I really don't knew what is wrong.

Related

How to change field to original value using a "reset" button in wpf

I have a class that has several properties, one of which is editable, another of which is calculated based on the editable value. I want to initialize the editable value with something and allow the user to change it however they wish. However, I also want to have a reset button that puts the original value back into the textbox. I have a third variable that stores the value of the original number. However, I am not sure how I am supposed to access the object when the reset button is clicked to put the value back into the textbox. I've put the relevant code below (if I shouldn't be posting everything please let me know, still new to stackoverflow how-to):
Main Window
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;
using HDR_BED_Calc_local.Testers;
using HDR_BED_Calc_local.Helpers;
namespace HDR_BED_Calc_local
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//var window = new MainWindow();
this.DataContext = new fraction_doses(800, 700, 900, 800, 900, 1, 3);
}
}
}
XAML
<Window x:Class="HDR_BED_Calc_local.MainWindow"
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:HDR_BED_Calc_local"
xmlns:uctesters="clr-namespace:HDR_BED_Calc_local.Testers"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<uctesters:fx_tester x:Name="fxtester_UC"/>
</Grid>
</Window>
Custom user control
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;
using HDR_BED_Calc_local.Helpers;
namespace HDR_BED_Calc_local.Testers
{
/// <summary>
/// Interaction logic for fx_tester.xaml
/// </summary>
public partial class fx_tester : UserControl
{
public fx_tester()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// What do I put here??
}
}
}
XAML
<UserControl x:Class="HDR_BED_Calc_local.Testers.fx_tester"
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:HDR_BED_Calc_local.Testers"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800" Background="White">
<StackPanel HorizontalAlignment="Center">
<StackPanel Orientation="Horizontal">
<TextBlock xml:space="preserve">Fraction: </TextBlock>
<TextBlock Text="{Binding Path=fraction_number}"></TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock xml:space="preserve">Current Dose: </TextBlock>
<TextBox x:Name="curr_fx_tb" Text="{Binding Path=editable_fraction_dose, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock xml:space="preserve">EQD2: </TextBlock>
<TextBlock Text="{Binding Path=this_fx_brachy_EQD2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
<Button Content="Reset" Click="Button_Click"/>
</StackPanel>
</UserControl>
Helper function with class
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace HDR_BED_Calc_local.Helpers
{
internal class fraction_doses : INotifyPropertyChanged
{
public int fraction_number { get; set; }
public double alpha_beta { get; }
private double _editable_fraction_dose;
public double editable_fraction_dose
{
get { return _editable_fraction_dose; }
set
{
_editable_fraction_dose = value;
calc_EQD2();
this.OnPropertyChanged("editable_fraction_dose");
}
}
public double actual_fraction_dose { get; }
public double pear_plan_dose { get; }
public double IMRT_plan_dose { get; }
public double max_dose_limit { get; }
public double preferred_dose_limit { get; }
private double _this_fx_brachy_EQD2;
public double this_fx_brachy_EQD2
{
get { return this._this_fx_brachy_EQD2; }
set
{
this._this_fx_brachy_EQD2 = value;
this.OnPropertyChanged("this_fx_brachy_EQD2");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public fraction_doses(double current_dose, double pear_dose, double IMRT_dose, double max_dose_limit, double preferred_dose_limit, int fraction_number, int alpha_beta)
{
this.alpha_beta = alpha_beta;
this.actual_fraction_dose = current_dose;
this.editable_fraction_dose = current_dose;
this.pear_plan_dose = pear_dose;
this.IMRT_plan_dose = IMRT_dose;
this.max_dose_limit = max_dose_limit;
this.preferred_dose_limit = preferred_dose_limit;
this.fraction_number = fraction_number;
}
public void calc_EQD2()
{
// EQD2 is always reported in Gray even though we will be reporting cGy
double dose_Gy = this.editable_fraction_dose/100;
this.this_fx_brachy_EQD2 = Math.Round(1 * dose_Gy * (1+ dose_Gy / alpha_beta)/(1+2/alpha_beta), 2);
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
You can try the following:
private void Button_Click(object sender, RoutedEventArgs e)
{
// What do I put here??
var dc = (fraction_doses ) this.DataContext:
if(dc!=null)
dc.Clear();
}
in your fraction_doses class add the method that clears the properties
public void Clear(){
this.MyProperty = MY_DEFAULT_VALUE;
//clear other properties..
}

In MVVM How can i binding list in MODEL to combobox?

In MODEL, there is a list<string>.
In VIEWMODEL, there is IList<MODEL>.
And I want to binding at ComboBox in VIEW
But when i binding ItemsSource to MODEL list, VIEW look to VIEWMODEL.
So binding alway fail.
How can solve this problem?
class Model
{
private IList<string> _comboItems;
public IList<string> ComboItems
{
get => _comboItems;
set => SetProperty(ref _comboItems, value);
}
}
class ViewModel
{
private IList<Model> _modelList;
public IList<Model> ModelList
{
get => _modelList;
set => SetProperty(ref _modelList, value);
}
}
VIEW
<....>
<GridView>
<GridViewComboBoxColumn ItemsSource="{binding ModelList}"/>
</GridView>
I guess that you have a datagrid and you want to populate a column by combobox with strings come from ComboItems. If this is your goal: you have to keep in mind the following points.
you have to set the DataContext pointing your
Your ViewModel has, at least implements INotifyPropertyChanged, however if you have to do a large use of mvvm I suggest you to use one mvvm framework like MVVM Light or Caliburn Micro there are many however
the ItemsSource of your datagrid have to be able to notify changes to your view, it has to be something like an ObservableCollection or a BindingList
If you want to change the comboboxitems at runtime add or remove or items also ComboBoxItems has to be a BindingList ... it is not very good to have bindinglist in a model.
well based on what I say you could do in this way I use traditional WPF your code seems to be UWP
MainWindow.xaml:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx /2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<DataGrid ItemsSource="{Binding ModelList}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" />
<DataGridTemplateColumn Header="MyComboColumn" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource ="{Binding ComboItems}" BorderThickness="0" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
MainWindow.xaml.cs
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.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ViewModel vm = new ViewModel();
DataContext = vm;
vm.ModelList = new BindingList<Model>();
Model md = new Model();
md.ComboItems = new List<string>();
md.ComboItems.Add("string1");
md.ComboItems.Add("string2");
md.ComboItems.Add("string3");
vm.ModelList.Add(md);
md = new Model();
md.ComboItems = new List<string>();
md.ComboItems.Add("string4");
md.ComboItems.Add("string5");
md.ComboItems.Add("string6");
vm.ModelList.Add(md);
}
}
}
ViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace WpfApplication2
{
public class ViewModel : INotifyPropertyChanged
{
private BindingList<Model> _modelList;
public BindingList<Model> ModelList
{
get { return _modelList; }
set { _modelList = value;
NotifyPropertyChanged("ModelList");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
}
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WpfApplication2
{
public class Model
{
private IList<string> _comboItems;
public IList<string> ComboItems
{
get { return _comboItems; }
set { _comboItems = value; }
}
}
}

Binding main class fails

i created a custom control in WPF for Windows 10 Apps. The problem is that the binding in the main class doesn't work. It binds to my custom control. Can anyone see the problem? How can i repair the code. It doesnt work. Specially the binding doesnt work. How can i solve that. I have no idea, how to fix that.
View Model
Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using AppDemo.Annotations;
namespace AppDemo
{
public class ViewModel : INotifyPropertyChanged
{
private String t1, t2;
public String T1
{
get { return t1; }
set
{
t1 = value;
Concat = T1 + T2;
}
}
public String T2
{
get { return t2; }
set
{
t2 = value;
Concat = T1 + T2;
}
}
private String concat;
public String Concat
{
get { return concat; }
set
{
concat = value;
OnPropertyChanged(nameof(Concat));
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
<UserControl
x:Class="AppDemo.ExampleControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppDemo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid Name="grid">
<StackPanel>
<TextBox Text="{Binding T1,Mode=TwoWay}"/>
<TextBox Text="{Binding T2,Mode=TwoWay}"/>
</StackPanel>
</Grid>
</UserControl>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using AppDemo.Annotations;
// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236
namespace AppDemo
{
public sealed partial class ExampleControl : UserControl
{
public static readonly DependencyProperty ConcatProperty = DependencyProperty.Register(
"Concat", typeof(String), typeof(ExampleControl), new PropertyMetadata(default(String)));
private ViewModel m;
public String Concat
{
get { return (String)GetValue(ConcatProperty); }
set { SetValue(ConcatProperty, value); }
}
public ExampleControl()
{
this.InitializeComponent();
m = new ViewModel();
grid.DataContext = m;
m.PropertyChanged += M_PropertyChanged;
}
private void M_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Concat = m.Concat;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
<Page
x:Class="AppDemo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppDemo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<local:ExampleControl Concat="{Binding C}"/>
<Button Name="btnTest" Click="BtnTest_OnClick">Test</Button>
</StackPanel>
</Grid>
</Page>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace AppDemo
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public String C { get; set; }
public MainPage()
{
this.InitializeComponent();
this.DataContext = this;
}
private void BtnTest_OnClick(object sender, RoutedEventArgs e)
{
String msg = C;
}
}
}
It is generally better to put your properties that you want to bind to, within their own distinct view-model class - not mixed in with your view code. This code is unnecessarily obtuse.
BTW...
Your UserControl named ExampleControl, has textboxes whose Text property is bound to T1 and T2. However, when you set either of those values - they set the Concat property but fail to raise the PropertyChanged event with their own name.
You'd fix that with, for example:
public String T1
{
set
{
t1 = value;
OnPropertyChanged(nameof(T1));
Concat = T1 + T2;
}
}
Set the Mode of the Binding to TwoWay in your MainPage:
<local:ExampleControl Concat="{Binding C, Mode=TwoWay}"/>

Unable to use MVVM/binding correctly in the below code and having issues with Icommand property

Very new to WPF coding using MVVM. Tried making a simple calculator in WPF using MVVM. But unable to trigger the Icommand in the below code.If possible help me in this. Grateful if anybody can help me out.
View Code:
<Window x:Class="MVVMCalculator.MainWindow"
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:MVVMCalculator"
mc:Ignorable="d"
Title="Calculator" Height="350" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="85"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBox Text="{Binding Display, Mode=OneWay}" IsReadOnly="True" TextWrapping="Wrap"
Grid.Row="0" Background="#E2E2E2" Margin="0,10,0,0" VerticalAlignment="Top"
Height="75" Width="250" HorizontalAlignment="Center" FontSize="22" FontWeight="Bold"
TextAlignment="Right">
<TextBox.Effect>
<DropShadowEffect/>
</TextBox.Effect>
</TextBox>
<ItemsControl Grid.Row="1" ItemsSource="{Binding Buttns}" Margin="15,15,15,10">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="5" Rows="4" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Txt, Mode=TwoWay}" Command="{Binding Enter_number}"
FontSize="18" FontWeight="Bold" Height="50" Width="50" Background="#eef2f3"
BorderBrush="Black" BorderThickness="1.0" Name="number">
<Button.Effect>
<DropShadowEffect/>
</Button.Effect>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
ViewModel Code:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace MVVMCalculator
{
class ViewModel : INotifyPropertyChanged
{
Buttons btn = new Buttons();
private decimal operand1;
private decimal operand2;
private string operation;
private decimal result;
private string display;
private bool newDisplayRequired = false;
ObservableCollection<Buttons> buttns;
public ObservableCollection<Buttons> Buttns
{
get { return buttns; }
set { buttns = value; }
}
public decimal Result
{
get { return result; }
}
public decimal Operand1
{
get { return operand1; }
set { operand1 = value; }
}
public decimal Operand2
{
get { return operand2; }
set { operand2 = value; }
}
public string Operation
{
get { return operation; }
set { operation = value; }
}
public string Display
{
get { return display; }
set { display = value;
OnPropertyChanged("Display");
}
}
public ViewModel()
{
buttns = new ObservableCollection<Buttons>
{
new Buttons("1"), new Buttons("2"), new Buttons("3"),
new Buttons("C"), new Buttons("Back"), new Buttons("4"),
new Buttons("5"), new Buttons("6"), new Buttons("CE"),
new Buttons("%"), new Buttons("7"), new Buttons("8"),
new Buttons("9"), new Buttons("/"), new Buttons("*"),
new Buttons("0"), new Buttons("."), new Buttons("+"),
new Buttons("-"), new Buttons("=")
};
display = "0";
operand1 = 0;
operand2 = 0;
operation = "";
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private ICommand enter_number;
public ICommand Enter_number
{
get
{
if(enter_number==null)
{
enter_number = new DelegateCommand<string>(MyAction, _canExecute);
}
return enter_number;
}
}
private static bool _canExecute(string button)
{
return true;
}
public void MyAction(string btn)
{
switch(btn)
{
case "C":
display = "0";
operand1 = 0;
operand2 = 0;
//operation = "";
break;
case ".":
if (!display.Contains("."))
{
Display = display + ".";
}
break;
case "Back":
if (display.Length > 1)
Display = display.Substring(0, display.Length - 1);
else Display = "0";
break;
default:
if (display == "0" || newDisplayRequired)
Display = btn;
else
Display = display + btn;
break;
}
}
}
}
Buttons Class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MVVMCalculator
{
class Buttons:INotifyPropertyChanged
{
private string txt;
public string Txt
{
get { return txt; }
set { txt = value; }
}
public Buttons(string a)
{
txt = a;
}
public Buttons()
{
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Xaml.cs:
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 MVVMCalculator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
}
Since the Enter_number property is defined in the ViewModel class you need to use a {RelativeSource} to be able to bind to it:
<Button Content="{Binding Txt, Mode=TwoWay}"
Command="{Binding DataContext.Enter_number, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
FontSize="18" FontWeight="Bold" Height="50" Width="50" Background="#eef2f3"
BorderBrush="Black" BorderThickness="1.0" Name="number">
<Button.Effect>
<DropShadowEffect/>
</Button.Effect>
</Button>
The default DataContext of the Button is the current Buttons object in the ItemsSource collection of the ItemsControl and that's why your binding fails.

items of the list lost after navigation in windows phone 8 c#

In my windows phone application, I have list that have all contacts like below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using GetContacts.Resources;
using Microsoft.Phone.UserData;
using Microsoft.Phone.Tasks;
using Windows.Phone.PersonalInformation;
using System.IO.IsolatedStorage;
namespace GetContacts
{
public partial class MainPage : PhoneApplicationPage
{
List<CustomContact> listOfContact = new List<CustomContact>();
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void ButtonContacts_Click(object sender, RoutedEventArgs e)
{
Contacts cons = new Contacts();
cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted);
cons.SearchAsync(String.Empty, FilterKind.None, "Contacts Test #1");
}
void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
listOfContact.Clear();
try
{
foreach (var c in e.Results)
{
CustomContact contact = new CustomContact();
contact.Name = c.DisplayName;
int count = c.PhoneNumbers.Count();
for (int i = 0; i < count; i++)
{
if (count > 0 && c.PhoneNumbers.ElementAt(i).PhoneNumber != null && !string.IsNullOrEmpty(c.PhoneNumbers.ElementAt(i).PhoneNumber) )
{
contact.Number[i]= c.PhoneNumbers.ElementAt(i).PhoneNumber.ToString();//.ToString();
}
else
{
contact.Number[i] = "";
}
}
listOfContact.Add(contact);
}
for (int i = 0; i < listOfContact.Count(); i++)
{
if(listOfContact1.Count != listOfContact.Count)
{
listOfContact1.Add(listOfContact.ElementAt(i));
}
}
ContactResultsData.ItemsSource = listOfContact;
}
catch (System.Exception)
{
//No results
}
if (ContactResultsData.Items.Any())
{
ContactResultsLabel.Text = "results";
}
else
{
ContactResultsLabel.Text = "no results";
}
}
private void hyplnk_Next_Click(object sender, RoutedEventArgs e)
{
PhoneApplicationService.Current.State["Contact"] = listOfContact;
NavigationService.Navigate(new Uri("/createGroups.xaml?Contact=" + listOfContact, UriKind.Relative));
}
}
}
below is the CustomContact class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using GetContacts.Resources;
using Microsoft.Phone.UserData;
using System.IO;
using System.Xml.Serialization;
namespace GetContacts
{
public class CustomContact
{
public string[] number = new string[5];
public string Name { get; set; }
public string[] Number
{
get { return number; }
set { number = value; }
}
public CustomContact()
{
}
public CustomContact( Contact contact)
{
Name = contact.DisplayName;
int count = contact.PhoneNumbers.Count();
for (int i = 0; i < count; i++)
{
if (count > 0 && contact.PhoneNumbers.ElementAt(i).PhoneNumber != null && !string.IsNullOrEmpty(contact.PhoneNumbers.ElementAt(i).PhoneNumber))
{
Number[i] = contact.PhoneNumbers.ElementAt(i).PhoneNumber.ToString();
}
else
{
Number[i] = "";
}
}
}
}
}
below is XAML page
<Grid x:Name="ContentPanel" Margin="12,0,12,0">
<StackPanel Height="Auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,10">
<TextBlock x:Name="ContactResultsLabel" Text="results are loading..." Style="{StaticResource PhoneTextLargeStyle}" TextWrapping="Wrap" />
<ListBox x:Name="ContactResultsData" ItemsSource="{Binding listOfContacts}" Height="293" Margin="24,0,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="ContactResultsName" Text="{Binding Name}" FontSize="50" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
<Grid Grid.Row="1">
<Button x:Name="ButtonContacts"
Content="Get All Contacts"
FontSize="15"
Width="200"
Height="70"
Background="AliceBlue"
Foreground="Blue"
HorizontalAlignment="Left"
Click="ButtonContacts_Click" Margin="27,30,0,322"></Button>
</Grid>
And in the hyplnk_Next_Click event, I navigate list to the next page but when I come back to the previous page the items of list are lost and the list is empty. what should I do to maintain the list of elements after navigation. Kindly suggest me.
Waiting for your reply.
Thanks.
You already save the transientState (the CustomContancts list), although your hyperlinkbutton handler is not the place to do it. I presume you're not loading it after you navigate back to the page with the contacts.
You should read and understand the Application Execution Model. It is crucial in Windows Phone development.
The place to save and load your page's state are the page's overriden methods OnNavigatedFrom OnNavigatedTo.
Here's an example
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (PhoneApplicationService.Current.State.Contains["Contact"])
{
listOfContact =
PhoneApplicationService.Current.State["Contact"] as List<CustomContact>();
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
PhoneApplicationService.Current.State["Contact"] = listOfContact;
}
OnNavigatedFrom is called whenever you navigate away from a page and OnNavigatedTo is called when you navigate to a page.

Categories