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}"/>
Related
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..
}
With the ability to view details through SelectItem...I do not understand how to binding them correctly ... Listbox exclusively for data output ... And I need that when you click on the menu item on the side, information from the database appears
XAML of listbox
<ListBox Height="800" ItemsSource="{Binding ProfilesList}"></ListBox>
MyOutputClass
using ExperimentProjectt.DB_DIRECT;
using ExperimentProjectt.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExperimentProjectt.Services
{
public class ProfilesSystem
{
public DBContextClass _context = new();
public List<User> GetAllUsers ()
{
List<User> allusers = _context.Userss.ToList();
return allusers;
}
}
}
MyViewModel:
using ExperimentProjectt.DB_DIRECT;
using ExperimentProjectt.Entities;
using ExperimentProjectt.Services;
using ExperimentProjectt.ViewModels.Base;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExperimentProjectt.ViewModels
{
public class ProfilesViewModel:ViewModelBase
{
private readonly ProfilesSystem _profilesSystem;
public ProfilesViewModel()
{
_profilesSystem = new ProfilesSystem();
}
private List<User> profileslist;
public List<User> ProfilesList
{
get
{
return profileslist = _profilesSystem.GetAllUsers();
}
set
{
profileslist = value;
OnPropertyChanged();
}
}
}
}
ObservableCollection already has intefaces: INotifyCollectionChanged, INotifyPropertyChanged.
public ObservableCollection<User> ProfilesList;
ProfilesList = new ObservableCollection<User>(_profilesSystem.GetAllUsers());
private User selectedItem;
public User SelectedItem
{
get { return selectedItem; }
set
{
selectedItem = value;
OnPropertyChanged();
}
}
then:
<ListBox SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding ProfilesList}"></ListBox>
example of data output:
<StackPanel>
<TextBlock Text="{Binding SelectedItem.Name}"/>
<TextBlock Text="{Binding SelectedItem.Username}"/>
<TextBlock Text="{Binding SelectedItem.Age}"/>
</StackPanel>
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; }
}
}
}
I'm writing a UWP app and have a few comboboxes bound to my view model. For some reason the comboboxes aren't updating the bound value nor loading it when they render if I set the values manually while debugging. I see that this is a common issue but I can't spot any of the causes I've seen other people have so far. Following is my stripped down code:
XAML:
<Page
x:Class="UWPApp.Scorekeeper.SelectGoalTime"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UWPApp.Scorekeeper"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="MainElement">
<Grid Background="{ThemeResource SystemControlBackgroundAccentBrush}">
<ComboBox x:Name="MinutesSelect" SelectedValue="{Binding ElementName=MainElement,Path=ViewModel.Minutes}" ItemsSource="{Binding ElementName=MainElement,Path=MinutesList}"/>
</Grid>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using UWPApp.Scorekeeper.Interfaces;
using UWPApp.Scorekeeper.Models.ViewModels;
using UWPApp.Scorekeeper.Models.TransportClasses;
using Windows.UI.Popups;
using UWPApp.Scorekeeper.Models;
using UWPApp.Scorekeeper.Toolbox;
namespace UWPApp.Scorekeeper
{
public sealed partial class SelectGoalTime : Page
{
public AddGoal_FVM ViewModel { get; set; }
public List<int> MinutesList { get; set; } = Enumerable.Range(0,21).ToList();
public SelectGoalTime()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var message = e.Parameter as GoalMessage;
ViewModel = message.ViewModel;
}
}
}
AddGoal_FVM
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace UWPApp.Scorekeeper.Models.ViewModels
{
public class AddGoal_FVM
{
public int Minutes { get; set; }
}
}
Since I don't have the reputation to add a comment, I'll have to share this way:
Found here, https://twitter.com/kdawg02/status/746734845393518592, BUG UWP ComboBox SelectedValue has to be the last property in XAML otherwise it will not set the value on load.
Hope it helps, I had no end of troubles with trying to bind a combobox in UWP with the MVVM pattern.
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.