My Combobox Selected Value binding doesn't flow back in Two Way Data binding - data-binding

Im Using Simple MVVM Framework to create a simple Silverlight 4.0 LOB Application.
I have an Employee List View that shows List Of all Employees in and i have in my EmployeeListViewModel some properties As Follow:
private Grade selectedGrade;
public Grade SelectedGrade
{
get { return selectedGrade; }
set
{
selectedGrade = value;
NotifyPropertyChanged(m => m.SelectedGrade);
}
}
private Religion selectedReligion;
public Religion SelectedReligion
{
get { return selectedReligion; }
set
{
selectedReligion = value;
NotifyPropertyChanged(m => m.SelectedReligion);
}
}
private ObservableCollection<Grade> grades;
public ObservableCollection<Grade> Grades
{
get { return grades; }
set
{
grades = value;
NotifyPropertyChanged(m => m.Grades);
}
}
private ObservableCollection<Religion> religions;
public ObservableCollection<Religion> Religions
{
get { return religions; }
set
{
religions = value;
NotifyPropertyChanged(m => m.Religions);
}
}
private ObservableCollection<Department> departments;
public ObservableCollection<Department> Departments
{
get { return departments; }
set
{
departments = value;
NotifyPropertyChanged(m => m.Departments);
}
}
private Employee selectedEmployee;
public Employee SelectedEmployee
{
get { return selectedEmployee; }
set
{
selectedEmployee = value;
SetCanProperties();
NotifyPropertyChanged(m => m.SelectedEmployee);
}
}
private ObservableCollection<Employee> employees;
public ObservableCollection<Employee> Employees
{
get { return employees; }
set
{
employees = value;
NotifyPropertyChanged(m => m.Employees);
}
}
private Department selectedDepartment;
public Department SelectedDepartment
{
get { return selectedDepartment; }
set
{
selectedDepartment = value;
NotifyPropertyChanged(m => m.SelectedDepartment);
}
}
now in my view i have a button to edit selected employee in my Employee List that opens up a new Child Window with the EmployeeDetails to Edit
EmployeeListViewModel viewModel;
public EmployeeListView()
{
InitializeComponent();
viewModel = (EmployeeListViewModel)DataContext;
}
and here is the edit employee Method
private void editItemButton_Click(object sender, RoutedEventArgs e)
{
// Exit if no product selected
if (viewModel.SelectedEmployee == null) return;
// Create a product detail model
EmployeeDetailViewModel detailModel =
new EmployeeDetailViewModel(viewModel.SelectedEmployee);
// set comboboxes !!
detailModel.Departments = viewModel.Departments;
detailModel.Religions = viewModel.Religions;
detailModel.Grades = viewModel.Grades;
// Start editing
detailModel.BeginEdit();
// Show EmployeeDetail view
EmployeeDetailView itemDetail = new EmployeeDetailView(detailModel);
itemDetail.Closed += (s, ea) =>
{
if (itemDetail.DialogResult == true)
{
// Confirm changes
detailModel.EndEdit();
}
else
{
// Reject changes
detailModel.CancelEdit();
}
};
itemDetail.Show();
}
now on my details Child View I have this Constractor
public EmployeeDetailView(EmployeeDetailViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
and here is my DetailsViewModel constractor
public EmployeeDetailViewModel(Employee model)
{
base.Model = model;
}
private ObservableCollection<Religion> religions;
public ObservableCollection<Religion> Religions
{
get { return religions; }
set
{
religions = value;
NotifyPropertyChanged(m => m.Religions);
}
}
private ObservableCollection<Grade> grades;
public ObservableCollection<Grade> Grades
{
get { return grades; }
set
{
grades = value;
NotifyPropertyChanged(m => m.Grades);
}
}
private ObservableCollection<Department> departments;
public ObservableCollection<Department> Departments
{
get { return departments; }
set
{
departments = value;
NotifyPropertyChanged(m => m.Departments);
}
}
after all this now comes the binding i have three comboboxes
for Departments, Religions and Grades (Which are foreign keys in my employee table)
<ComboBox ItemsSource="{Binding Departments}" DisplayMemberPath="DepartmentName" SelectedValue="{Binding Model.Emp_Department, Mode=TwoWay}" SelectedValuePath="DepartmentId"/>
<ComboBox ItemsSource="{Binding Grades}" DisplayMemberPath="GradeName" SelectedValue="{Binding Model.Emp_Grade, Mode=TwoWay}" SelectedValuePath="GradeId"/>
and so on .. The problem is that only the Departments combo box is updating the source value when i change its value
and the other combo boxes don't .. even when the binding statement is exactly the same !!
so sorry for writing so much .. but can anyone help me with this ??
thanks a lot

Unfortunately your MVVM separation is a little messed up as you are binding from the View directly to the underlying Model (meaning any business logic / validation in the ViewModel) is bypassed.
However, you seem to have everything in place so I would suggest the following:
Change your Xaml to this (note the change from SelectedValue to SelectedItem):
<ComboBox ItemsSource="{Binding Departments}" DisplayMemberPath="DepartmentName" SelectedItem="{Binding SelectedDepartment, Mode=TwoWay}"/>
<ComboBox ItemsSource="{Binding Grades}" DisplayMemberPath="GradeName" SelectedItem="{Binding SelectedGrade, Mode=TwoWay}"/>
Then within the setter of the SelectedDepartment/SelectedGrade properties, perform any required validation and then write the Id of the selected item to the properties in your (detail) model.
Hope it helps.

well here is how i do my combos:
<ComboBox ItemsSource="{Binding Path=ListPeople, UpdateSourceTrigger= PropertyChanged}" SelectedItem="{Binding Path=SelectedPerson, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="FirstName"/>
and in my viewmodel:
private ObservableCollection<Person> listPeople = new ObservableCollection<Person>();
public IEnumerable<Person> ListPeople
{
get { return this.listPeople; }
}
public Person SelectedPerson
{
get { return selectedPerson; }
set
{
selectedPerson = value;
if (selectedPerson != null)
{
NextToPayID = selectedPerson.PersonID;
}
base.RaisePropertyChanged("SelectedPerson");
}
}
see if you can use that to help!

Related

Avalonia Datagrid cell value does not update when model property is updated from another column

I have a Datagrid with two columns that bind to the same property
<DataGrid
Margin="10"
BorderBrush="Black"
BorderThickness="1"
Grid.Row="1"
Grid.ColumnSpan="3"
Items="{Binding Logs}"
AutoGenerateColumns="False"
>
<DataGrid.Columns>
<DataGridTextColumn
Header="Temp Date"
Binding="{Binding Date,Mode=TwoWay}"
>
</DataGridTextColumn>
<DataGridTemplateColumn
Header="Calendar Column"
CellTemplate="{Binding TestTemplate}"
CellEditingTemplate="{Binding EditingTemplate}"
>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
I have also created a cell template in the view model as such:
// Cell Data Template
TestTemplate = new FuncDataTemplate<EntryLog>((value, namescope) =>
new TextBlock
{
[!TextBlock.TextProperty] = new Binding("Date",BindingMode.TwoWay),
});
// Cell Editing Data Template
EditingTemplate = new FuncDataTemplate<EntryLog>((value, namescope) =>
{
var grid = new Grid();
var tb = new TextBlock
{
[!TextBlock.TextProperty] = new Binding("Date", BindingMode.TwoWay),
};
grid.Children.Add(tb);
var calendar = new Calendar();
calendar.DisplayDate = value.Date;
calendar.SelectedDate = value.Date;
Popup popup = new Popup();
popup.Child = calendar;
popup.IsOpen = true;
calendar.SelectedDatesChanged += (s, e) =>
{
value.Date = calendar.SelectedDate.Value.Date;
//tb.Text = value.Date.ToString();
};
grid.Children.Add(popup);
return grid;
});
In the UI, it looks like this when editing:
My issue is, whenever I update one column, the other column does not get updated. The itemsource is a Observable Collection of my model
My model:
public class EntryLog : INotifyPropertyChanged
{
private DateTime _date;
public DateTime Date
{
get => _date;
set
{
if (_date != value)
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Date)));
_date = value;
}
}
public string Description { get; set; }
public double Hours { get; set; }
public event PropertyChangedEventHandler? PropertyChanged;
}
Was wondering if anyone can help me out? Maybe I'm missing something that I just can't identify.
Silly me, I was invoking the propertychanged event before the change of the actual value. The correct way is just to swap that:
public class EntryLog : INotifyPropertyChanged
{
private DateTime _date;
public DateTime Date
{
get => _date;
set
{
if (_date != value)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Date)));
_date = value;
}
}
}
public string Description { get; set; }
public double Hours { get; set; }
public event PropertyChangedEventHandler? PropertyChanged;
}

SearchBar and Xamarin.Form

Am working on a XF project which has a SearchBar. The XAML Declaration looks like following.
<SearchBar Placeholder="Result" Text="{Binding SearchedCustomer,Mode=TwoWay}"
SearchCommand="{Binding SearchCustomerCommand}"></SearchBar>
At ViewModel, I have following declared
private string _SearchedCustomer;
public string SearchedCustomer
{
get { return _SearchedCustomer; }
set { SetProperty(ref _SearchedCustomer, value); }
}
public DelegateCommand SearchCustomerCommand { get; set; }
private ObservableCollection<CustomerModel> _CustomerList;
public ObservableCollection<CustomerModel> CustomerList
{
get
{
if (_CustomerList == null)
FillCustomerDetails();
return _CustomerList;
}
set { SetProperty(ref _CustomerList, value); }
}
private void ExecuteSearchCustomerCommand()
{
var tempRecords = _CustomerList.Where(c => c.ReferenceText.Contains(SearchedCustomer));
CustomerList.Clear();
foreach (var item in tempRecords)
{
CustomerList.Add(item);
}
}
I also have the SearchCustomerCommand created in the Constructor as following
SearchCustomerCommand = new DelegateCommand(ExecuteSearchCustomerCommand).ObservesProperty(()=> SearchedCustomer);
When I type in the SearchBar, the SearchedCustomer Fields gets changed, however, the Command SearchCustomerCommand is not executed.
Could someone help me in identifying what I am doing wrong here ?

xamarin design time binding cannot resolve property in data context

i'm currently in the process of modifying an ItemsView according to my needs. I noticed on flaw in my implementation however:
Unlike ListView i don't get intellisense according to my current iteration element. Does anyone know how to make that happen?
Here's my control implementation:
// http://adventuresinxamarinforms.com/2015/04/29/creating-a-xamarin-forms-accordion-control-without-custom-renders/
public class ItemsView : Grid
{
protected ScrollView ScrollView;
protected readonly StackLayout ItemsStackLayout;
public ItemsView()
{
ScrollView = new ScrollView();
ScrollView.SetBinding(ScrollOrientationProperty, new Binding(nameof(ScrollOrientation), mode: BindingMode.OneWay, source: this));
ItemsStackLayout = new StackLayout
{
Padding = new Thickness(0),
Spacing = 0,
HorizontalOptions = LayoutOptions.FillAndExpand
};
ItemsStackLayout.SetBinding(StackOrientationProperty, new Binding(nameof(ItemsStackLayout), mode: BindingMode.OneWay, source: this));
ScrollView.Content = ItemsStackLayout;
Children.Add(ScrollView);
SelectedCommand = new Command<object>(item =>
{
var selectable = item as ISelectable;
if (selectable == null)
return;
SetSelected(selectable);
SelectedItem = selectable.IsSelected ? selectable : null;
});
}
protected virtual void SetSelected(ISelectable selectable)
{
selectable.IsSelected = true;
}
public bool ScrollToStartOnSelected { get; set; }
#region SelectedCommand
public static BindableProperty SelectedCommandProperty = BindableProperty.Create<ItemsView, ICommand>(d => d.SelectedCommand, default(ICommand));
public ICommand SelectedCommand
{
get { return (ICommand) GetValue(SelectedCommandProperty); }
set { SetValue(SelectedCommandProperty, value); }
}
#endregion SelectedCommand
#region ScrollOrientation
public static BindableProperty ScrollOrientationProperty = BindableProperty.Create<ItemsView, ScrollOrientation>(d => d.ScrollOrientation, ScrollOrientation.Vertical);
public ScrollOrientation ScrollOrientation
{
get { return (ScrollOrientation) GetValue(ScrollOrientationProperty); }
set { SetValue(ScrollOrientationProperty, value); }
}
#endregion ScrollOrientation
#region StackOrientation
public static BindableProperty StackOrientationProperty = BindableProperty.Create<ItemsView, StackOrientation>(d => d.StackOrientation, StackOrientation.Vertical);
public StackOrientation StackOrientation
{
get { return (StackOrientation) GetValue(StackOrientationProperty); }
set { SetValue(StackOrientationProperty, value); }
}
#endregion StackOrientation
public event EventHandler SelectedItemChanged;
public static readonly BindableProperty ItemsSourceProperty =
BindableProperty.Create<ItemsView, IEnumerable>(p => p.ItemsSource, default(IEnumerable<object>), BindingMode.OneWay, null, ItemsSourceChanged);
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static readonly BindableProperty SelectedItemProperty =
BindableProperty.Create<ItemsView, object>(p => p.SelectedItem, default(object), BindingMode.TwoWay, null, OnSelectedItemChanged);
public object SelectedItem
{
get { return (object)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
public static readonly BindableProperty ItemTemplateProperty =
BindableProperty.Create<ItemsView, DataTemplate>(p => p.ItemTemplate, default(DataTemplate));
public DataTemplate ItemTemplate
{
get { return (DataTemplate)GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
private static void ItemsSourceChanged(BindableObject bindable, IEnumerable oldValue, IEnumerable newValue)
{
var itemsLayout = (ItemsView)bindable;
itemsLayout.SetItems();
var newObservableCasted = newValue as INotifyCollectionChanged;
var oldObservableCasted = oldValue as INotifyCollectionChanged;
if (newObservableCasted != null)
newObservableCasted.CollectionChanged += itemsLayout.ItemsSourceCollectionChanged;
if (oldObservableCasted != null)
oldObservableCasted.CollectionChanged -= itemsLayout.ItemsSourceCollectionChanged;
}
private void ItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
this.SetItems();
}
protected virtual void SetItems()
{
ItemsStackLayout.Children.Clear();
if (ItemsSource == null)
return;
foreach (var item in ItemsSource)
{
var itemView = GetItemView(item);
if (itemView == null)
{
ItemsStackLayout.Children.Add(new Label()
{
Text = "ItemTemplate missing."
});
break;
}
ItemsStackLayout.Children.Add(itemView);
}
SelectedItem = ItemsSource.OfType<ISelectable>().FirstOrDefault(x => x.IsSelected);
}
protected virtual View GetItemView(object item)
{
if (ItemTemplate == null)
return null;
ItemTemplate.SetValue(BindingContextProperty, item);
var content = ItemTemplate.CreateContent();
var view = content as View;
if (view == null)
return null;
var gesture = new TapGestureRecognizer
{
CommandParameter = item
};
gesture.SetBinding(TapGestureRecognizer.CommandProperty, (ItemsView v) => v.SelectedCommand, BindingMode.OneWay);
AddGesture(view, gesture);
return view;
}
protected void AddGesture(View view, TapGestureRecognizer gesture)
{
view.GestureRecognizers.Add(gesture);
var layout = view as Layout<View>;
if (layout == null)
return;
foreach (var child in layout.Children)
AddGesture(child, gesture);
}
private static void OnSelectedItemChanged(BindableObject bindable, object oldValue, object newValue)
{
var itemsView = (ItemsView)bindable;
if (newValue == oldValue)
return;
var selectable = newValue as ISelectable;
itemsView.SetSelectedItem(selectable ?? oldValue as ISelectable);
}
protected virtual void SetSelectedItem(ISelectable selectedItem)
{
var items = ItemsSource;
foreach (var item in items.OfType<ISelectable>())
item.IsSelected = selectedItem != null && item == selectedItem && selectedItem.IsSelected;
var handler = SelectedItemChanged;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
my viewmodels:
public class InfoFieldsViewModel : HeaderedViewModel
{
public override Task NavigatedToAsync(object state)
{
base.NavigatedToAsync(state);
var casted = state as SiteSelectionEntry;
if (casted != null)
{
HeaderText = $" < {casted.Name}";
}
Groups.IsEventNotificationEnabled = false;
var group = new InfoFieldGroupViewModel("Gruppe 1");
group.Items.Add(new InfoFieldDetailViewModel("Label1"));
group.Items.Add(new InfoFieldDetailViewModel("Label2"));
group.Items.Add(new InfoFieldDetailViewModel("Label3"));
Groups.Add(group);
group = new InfoFieldGroupViewModel("Gruppe 2");
group.Items.Add(new InfoFieldDetailViewModel("Label4"));
group.Items.Add(new InfoFieldDetailViewModel("Label5"));
group.Items.Add(new InfoFieldDetailViewModel("Label6"));
Groups.Add(group);
Groups.IsEventNotificationEnabled = true;
Groups.RaiseUpdate();
return Done;
}
private ExtendedObservableCollection<InfoFieldGroupViewModel> _groups = new ExtendedObservableCollection<InfoFieldGroupViewModel>();
public ExtendedObservableCollection<InfoFieldGroupViewModel> Groups
{
get { return GetValue(ref _groups); }
set { SetValue(ref _groups, value); }
}
}
public class EditableViewModel : ViewModelBase
{
private bool _isInEditMode = new bool();
public bool IsInEditMode
{
get { return GetValue(ref _isInEditMode); }
set { SetValue(ref _isInEditMode, value); }
}
}
public class InfoFieldGroupViewModel : ViewModelBase
{
public InfoFieldGroupViewModel()
{
IsExpanded = true;
}
public InfoFieldGroupViewModel(string groupName)
{
_groupName = groupName;
}
private bool _isExpanded = new bool();
public bool IsExpanded
{
get { return GetValue(ref _isExpanded); }
set { SetValue(ref _isExpanded, value); }
}
private string _groupName;
public string GroupName
{
get { return _groupName; }
set { SetValue(ref _groupName, value); }
}
private ExtendedObservableCollection<InfoFieldDetailViewModel> _items = new ExtendedObservableCollection<InfoFieldDetailViewModel>();
public ExtendedObservableCollection<InfoFieldDetailViewModel> Items
{
get { return GetValue(ref _items); }
set { SetValue(ref _items, value); }
}
}
public class InfoFieldDetailViewModel : EditableViewModel
{
public InfoFieldDetailViewModel()
{
}
public InfoFieldDetailViewModel(string label)
{
_label = label;
}
private string _label;
public string Label
{
get { return _label; }
set { SetValue(ref _label, value); }
}
}
The view which uses the controls:
<Grid BackgroundColor="{x:Static resources:Colors.DefaultBackground}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<custom:ApplicationHeader
HeaderText="{Binding HeaderText}"
HeaderTapCommand="{Binding NavigatorBackCommand}"
HomeButtonCommand="{Binding NavigatorBackCommand}"/>
<Grid Row="1" custom:GridExtensions.IsBusy="{Binding IsBusy}">
<custom:ItemsView ItemsSource="{Binding Groups}">
<custom:ItemsView.ItemTemplate>
<DataTemplate>
<Label MinimumHeightRequest="30" Text="{Binding GroupName}"></Label>
</DataTemplate>
</custom:ItemsView.ItemTemplate>
</custom:ItemsView>
</Grid>
</Grid>
Screenshot of designtime error:
Oddly enough an ordinary xamarin.forms listview seems to have no trouble getting the design time correct here and mapping the child datacontext within the item template.
Is there some attribute i'm missing out on to make it work? Or am i doing something wrong in my implementation which makes this fail? The template itself renders just fine. So it's just the design time getting it wrong here.
Any ideas welcome. So far none of my binding context redirects worked successfully.
For me, it was a design-time DataType specification added on page level:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:**;assembly=**"
xmlns:bindingConverters="clr-namespace:**;assembly=**"
x:DataType="viewModels:WelcomeViewModel" <!-- HERE-->
x:Class="**.WelcomePage"
Title="{Binding Title}">
<ContentPage.Content >
<CollectionView ItemsSource="{Binding Items}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Label Grid.Row="0" Grid.Column="0" Text="{Binding Name}"/> <!-- this binding was looking for property 'Name' on root level, which is 'WelcomeViewModel' -->
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ContentPage.Content>
</ContentPage>
So, I've just removed x:DataType="viewModels:WelcomeViewModel" and it started working.

How to refresh data grid with new search results with MVVM Light

I'm using the latest MMVM Light windows 8 binaries and VS 2012 latest updates, so all is good there. I'm new to the MVVM Light framework, so it's an adjustment.
I have a Customers page with a grid that is searched with a textbox and button - the text box is bound and the button uses a command. The data is showing up in the view model just fine. I LINQ over the Customers List and set the Customers list property - all works well. The problem is, the page doesn't refresh. When I go to another page and return to the Customers page, the searched data is displayed.
I suspect the view model is static and needs to re-instantiated.
The follow are the respective code frags:
public partial class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
}
else
{
SimpleIoc.Default.Register<IDataService, DataService>();
}
// Services
SimpleIoc.Default.Register<INavigationService, NavigationService>();
SimpleIoc.Default.Register<IMessenger, Messenger>();
// View Models
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<CustomersViewModel>();
SimpleIoc.Default.Register<CustomerViewModel>(true);
SimpleIoc.Default.Register<ContactsViewModel>();
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public CustomersViewModel Customers
{
get
{
return ServiceLocator.Current.GetInstance<CustomersViewModel>();
}
}
public CustomerViewModel Customer
{
get
{
return ServiceLocator.Current.GetInstance<CustomerViewModel>();
}
}
public ContactsViewModel Contacts
{
get
{
return ServiceLocator.Current.GetInstance<ContactsViewModel>();
}
}
public static void Cleanup()
{
}
}
}
public class CustomersViewModel : ViewModelBase
{
private readonly IDataService _dataService;
private INavigationService _navigationService;
private IMessenger _messenger;
public RelayCommand<string> RefreshClickCommand { get; set; }
public RelayCommand<string> SearchCustomersCommand { get; set; }
public const string CustomersPropertyName = "Customers";
private ObservableCollection<Customer> _customers = null;
public ObservableCollection<Customer> Customers
{
get
{
return _customers;
}
set
{
if (_customers == value)
{
return;
}
_customers = value;
RaisePropertyChanging(CustomersPropertyName);
}
}
public const string WelcomeTitlePropertyName = "WelcomeTitle";
private string _welcomeTitle = string.Empty;
public string WelcomeTitle
{
get
{
return _welcomeTitle;
}
set
{
if (_welcomeTitle == value)
{
return;
}
_welcomeTitle = value;
RaisePropertyChanged(WelcomeTitlePropertyName);
}
}
public const string CustomerSearchTermPropertyName = "CustomerSearchTerm";
private string _customerSearchTerm = string.Empty;
public string CustomerSearchTerm
{
get
{
return _customerSearchTerm;
}
set
{
if (_customerSearchTerm == value)
{
return;
}
_customerSearchTerm = value;
RaisePropertyChanging(CustomerSearchTermPropertyName);
}
}
public Customer SelectedItem
{
set
{
Customer customer = value;
_messenger.Send<Customer>(customer, "Customer");
_navigationService.Navigate(typeof(CustomerPage));
}
}
public CustomersViewModel(IDataService dataService)
{
_navigationService = SimpleIoc.Default.GetInstance<INavigationService>();
_messenger = SimpleIoc.Default.GetInstance<IMessenger>();
_dataService = dataService;
_dataService.GetData(
(item, error) =>
{
if (error != null)
{
// Report error here
return;
}
WelcomeTitle = item.Title + "Customers";
});
GetCustomers();
InitializeCommands();
}
private void InitializeCommands()
{
RefreshClickCommand = new RelayCommand<string>((item) =>
{
GetCustomers();
});
SearchCustomersCommand = new RelayCommand<string>((item) =>
{
SearchCustomers();
});
}
private void GetCustomers()
{
_customers = _dataService.GetCustomers();
}
private void SearchCustomers()
{
var cust = _dataService.GetCustomers();
List<Customer> customers = (from c in cust
where c.CompanyName.StartsWith(_customerSearchTerm)
orderby c.CompanyName
select c).ToList();
_customers = new ObservableCollection<Customer>(customers);
}
}
<common:LayoutAwarePage x:Class="SalesAccountManager.Views.RelationshipManager.CustomersPage"
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:common="using:SalesAccountManager.Common"
xmlns:ignore="http://www.ignore.com"
xmlns:telerikGrid="using:Telerik.UI.Xaml.Controls.Grid"
xmlns:WinRtBehaviors="using:WinRtBehaviors"
xmlns:Win8nl_Behavior="using:Win8nl.Behaviors"
mc:Ignorable="d ignore"
d:DesignHeight="768"
d:DesignWidth="1366"
DataContext="{Binding Customers, Source={StaticResource Locator}}">
....
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<TextBlock Text="Customers" FontFamily="Segoe UI" FontSize="38"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0, 0, 100, 0">
<TextBox Height="20" Width="600" Background="White" Text="{Binding CustomerSearchTerm, Mode=TwoWay}" />
<Button Background="White" Command="{Binding SearchCustomersCommand}">
<Image Source="../../Images/Search.jpg" Height="20" Width="20"></Image>
</Button>
</StackPanel>
</Grid>
Any guidance on this would be appreciated...
Thanks!

How to access datagrid in View from ViewModel in Silverlight?

Hai i'm doing one silverlight app that uses MVVM architecture.
The Scenario is this. I have one combobox and datagrid in same page.
I have use ObservableCollection to bind the values in Datagrid and in that collection i have three fields namely Fname,Sname and Dept.
I bind Dept in Combobox but if i select any one of department means that value does not update in DataGrid. ie., i have created the code in ViewModel and i use LINQ query and i have Fetched the value also in,
var semp = from s in Employees where s.Dept.Equals(Names.Dept) select s;
i need to send this semp datasource to Datagrid in View.
Datagrid Syntax is :
<my:DataGrid x:Name="McDataGrid" ItemsSource="{Binding Employees,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Margin="130,151,0,0" Height="137" VerticalAlignment="Top" RowBackground="#AA5D9324" AutoGenerateColumns="True" HorizontalAlignment="Left" Width="196">
</my:DataGrid>
Help me if u Know...
This is the ViewModel Code:
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.Collections.ObjectModel;
using System.ComponentModel;
using Silverlight_MVVM.Model;
using Silverlight_MVVM.Utils;
using System.Linq;
using System.Collections.Generic;
namespace Silverlight_MVVM.ViewModel
{
public class EmployeeListViewModel:INotifyPropertyChanged
{
public ObservableCollection<Employee> Employees { get; private set; }
public EmployeeListViewModel()
{
Employees = Silverlight_MVVM.DataHelper.EmployeeDataHelper.EmployeeData ();
}
private string _fname;
public string Fname
{
get
{
return _fname;
}
set
{
_fname = value;
RaisePropertyChanged("Fname");
}
}
private string _sname;
public string Sname
{
get
{
return _sname;
}
set
{
_sname = value;
RaisePropertyChanged("Sname");
}
}
private string _dept;
public string Dept
{
get
{
return _dept;
}
set
{
_dept = value;
RaisePropertyChanged("Dept");
}
}
private Employee _SelectedEmployee;
public Employee SelectedEmployee
{
get
{
return _SelectedEmployee;
}
set
{
_SelectedEmployee = value;
RaisePropertyChanged("SelectedEmployee");
}
}
private string _demp;
public string demp
{
get
{
return _demp;
}
set
{
_demp = value;
RaisePropertyChanged("demp");
}
}
private Employee _Names;
public Employee Names
{
get
{
return _Names;
}
set
{
_Names = value;
List<Employee> myList = new List<Employee>();
IEnumerable<Employee> myEnumerable = myList;
// List<Employee> listAgain = myEnumerable.ToList();
// Employees = (ObservableCollection<Employee>)Employees.Where(_ => _.Dept.Equals(Names.Dept));
RaisePropertyChanged("Names");
}
}
public void HandleShowMessage()
{
// MessageBox.Show("Hello " + Names + ",Welcome to EventTrigger for MVVM.");
}
public RelayCommand _AddEmployeeCommand;
/// <summary>
/// Returns a command that show the customer.
/// </summary>
public ICommand AddEmployeeCommand
{
get
{
if (_AddEmployeeCommand == null)
{
_AddEmployeeCommand = new RelayCommand(
param => this.AddEmployee(),
param => this.CanAddEmployee
);
}
return _AddEmployeeCommand;
}
}
public bool CanAddEmployee
{
get
{
return true;
}
}
public void AddEmployee()
{
Employee newEmployee = new Employee();
if (Names == null)
{
newEmployee.Fname = this.Fname;
newEmployee.Sname = this.Sname;
newEmployee.Dept = this.Dept;
Employees.Add(newEmployee);
//SelectedEmployee = newEmployee.ToString();
}
else //This is the event for getting selected item through combobox and the linq query fetching
{
Employees = Silverlight_MVVM.DataHelper.EmployeeDataHelper.EmployeeData();
var semp = from emp in Employees where emp.Dept.Equals(Names.Dept) select emp;
}
}
#region INotifyPropertyChanged
// [field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}

Resources