MVVMLight Toolkit changes not reflected when property is changed - c#

I'm using the MVVMLight Toolkit in my WPF project. All my ViewModels derive from the toolkit's ViewModelBase class, which implements the INotifyPropertyChanged for you and does all the notify work.
My current setup is extremely simple. I have a Person class with a single Name property.
public class Person
{
public string Name { get; set; }
}
My window has a TextBlock and a Button, and to the TextBlock I bind the Name property of the Person class object that I have. DataContext is set using a ViewModelLocator class.
<Window x:Class="BindingTest.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:ignore="http://www.galasoft.ch/ignore"
mc:Ignorable="d ignore"
Height="300" Width="300"
Title="MVVM Light Application"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center"
Text="{Binding Contact.Name}"/>
<Button Grid.Row="1" Content="Click" Command="{Binding ClickCommand}"/>
</Grid>
</Window>
In my ViewModel, I set the Name to Tom in the constructor, and change it when the button is clicked. I expect Tom to show up in the TextBlock when window is loaded (which it does), and to be changed to Jane when the button is clicked (which it doesn't).
public class MainViewModel : ViewModelBase
{
private Person _contact = new Person();
public Person Contact
{
get { return _contact; }
set { Set(ref _contact, value); }
}
public RelayCommand ClickCommand { get; private set; }
public MainViewModel(IDataService dataService)
{
Contact = new Person() { Name = "Tom" };
ClickCommand = new RelayCommand(Click);
}
public void Click()
{
Contact.Name = "Jane";
}
}
What am I missing?

Setting Contact.Name does not trigger the INotifyPropertyChanged.NotifyChanged event as the Contact setter is not executed. You could fix this using by one of the following techniques:
Implement INotifyPropertyChanged also in your model class
public class Person : INotifyPropertyChanged
{
private string _name;
public string Name
{
get => _name;
set
{
_name = value;
if (PropertyChanged != null)
PropertyChanged(this, nameof(Name));
}
}
public event PropertyChangedHandler PropertyChanged;
}
Or wrap the PersonClass in a PersonViewModel
public class PersonViewModel : ViewModelBase
{
private readonly Person _person;
public PersonViewModel(Person person)
{
_person = person;
}
public string Name
{
get => _person.Name;
set
{
var name = _person.Name;
if (Set(ref name, value))
_person.Name = name;
}
}
}
and in MainViewModel:
private PersonViewModel _contactViewModel
public PersonViewModel Contact
{
get { return _contactViewModel ?? (_contactViewModel = new PersonViewModel(_contact)); }
}
Or create a separate ContactName property in the MainViewModel
... and using ContactName instead of Contact.Name in the binding and the Click event handler.
public string ContactName
{
get { return _contact.Name; }
set
{
var name = _contact.Name;
if (Set(ref name, value))
_contact.Name = name;
}
}

Related

Set up a binding between two properties in code behind

In my view, I have a ListBox with some templated items that contain buttons.
<ListBox x:Name="MyListBox" ItemTemplate="{DynamicResource DataTemplate1}"
ItemsSource="{Binding MyItems}">
</ListBox>
And the template for generated items:
<DataTemplate x:Key="DataTemplate1">
<StackPanel Orientation="Horizontal">
<Button Width="50" Click="Button_Click" />
</StackPanel>
</DataTemplate>
When user clicks a button on one of those ListBox items, I want to send the index of that ListBox item to my ViewModel.
So figured to use Binding as it seems to be the way in MVVM. But I'm struggling to set up a binding in code between two properties.
My View code is as follows:
public partial class ItemView : UserControl
{
ViewModel.ItemViewModel VM;
public ItemView()
{
InitializeComponent();
VM = new ViewModel.ItemViewModel();
this.DataContext = VM;
}
private int clickedItemIndex;
public int ClickedItemIndex { get => clickedItemIndex; set => clickedItemIndex = value; }
private void Button_Click(object sender, RoutedEventArgs e)
{
var ClickedItem = (sender as FrameworkElement).DataContext;
ClickedItemIndex = MyListBox.Items.IndexOf(ClickedItem);
}
}
I get the index and set it to ClickedItemIndex property,
I also have property in my ViewModel:
public int SomeInt { get; set; }
Now how do I set up a binding between these two properties?
I'm quite new to MVVM and still learning it. So, maybe this not the correct approach. But I need to have a way for each individual listbox item to be able to call upon an effect in more global viewmodel. For example, if I wanted to have a "Remove" button on each of the listbox items, I would somehow need to send the index to the viewmodel and call the removeItem method with index as the parameter. Or is there a better way to do similar things?
I have a sample app created just for this scenario. I know it seems a lot of code at first glance. Copy this code in your project, that will help debug and get a hang of it(MVVM, databinding, commands and so on).
usercontrol.xaml
<UserControl x:Class="WpfApplication1.UserControl1"
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:WpfApplication1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.Resources>
<DataTemplate DataType="{x:Type local:Model}">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=Name}"/>
<Button Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DataContext.UpdateCommand}"
CommandParameter="{Binding}"
Content="Update"/>
<Button Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DataContext.RemoveCommand}"
CommandParameter="{Binding}"
Content="Remove"/>
</StackPanel>
</DataTemplate>
</Grid.Resources>
<ListBox ItemsSource="{Binding Models}">
</ListBox>
</Grid>
usercontrol.cs
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
View model
public class ViewModel : INotifyPropertyChanged
{
private Models _Models;
public Models Models
{
get { return _Models; }
set { _Models = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Models)));
}
}
public ViewModel()
{
Models = new Models();
UpdateCommand = new Command(o => true, UpdateItem);
RemoveCommand = new Command(o => true, RemoveItem);
}
void RemoveItem(object item)
{
Model m = (item as Model);
Models.Remove(m);
}
void UpdateItem(object item)
{
Model m = (item as Model);
m.Name = m.Name + " updated";
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public ICommand UpdateCommand { get; private set; }
public ICommand RemoveCommand { get; private set; }
}
Icommand implementation
public class Command : ICommand
{
private readonly Func<object, bool> _canExe;
private readonly Action<object> _exe;
public Command(Func<object,bool> canExecute,Action<object> execute)
{
_canExe = canExecute;
_exe = execute;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return _canExe(parameter);
}
public void Execute(object parameter)
{
_exe(parameter);
}
}
Model and a collection of models
public class Models : ObservableCollection<Model>
{
public Models()
{
Add(new Model ());
Add(new Model ());
Add(new Model ());
Add(new Model ());
}
}
public class Model : INotifyPropertyChanged
{
static int count = 0;
public Model()
{
Name = "Model "+ ++count;
}
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
You don't need to use a Button in order to select the item. When you click/tap on the item it will get automatically selected.
Then simply bind ListBox.SelectedIndex to your view model property SomeInt and it will update on every selection.
Data binding overview in WPF
You can also get the item itself by binding ListBox.SelectedItem to your view model.
You can handle new values by invoking a handler from the property's set method:
ViewModel.cs
class ViewModel : INotifyPropertyChanged
{
private int currentItemIndex;
public int CurrentItemIndex
{
get => this.currentItemIndex;
set
{
this.currentItemIndex = value;
OnPropertyChanged();
// Handle property changes
OnCurrentItemIndexChanged();
}
}
private MyItem currentItem;
public MyItem CurrentItem
{
get => this.currentItem;
set
{
this.currentItem = value;
OnPropertyChanged();
}
}
protected virtual void OnCurrentItemIndexChanged()
{
// Handle the new this.CurrentItemIndex value
}
// Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
ItemView .xaml
<UserControl>
<UserControl.DataContext>
<ViewModel />
</UserControl.DataContext>
<ListBox ItemsSource="{Binding MyItems}"
SelectedIndex="{Binding CurrentItemIndex}"
SelectedItem="{Binding CurrentItem}" />
</UserControl>

Accessing Properties of Properties in DataBinding

I have two public properties Foo and Bar in my ViewModel. Foo is just a string and Bar is a class that has a public property Name which is a string.
I want to bind Bar.Name to some GUI element. How do I do that?
<Label Content="{Binding Foo}"> writes the string Foo into the Label, as expected.
But <Label Content="{Binding Bar.Name}"> does not write the name of Bar into the Label. Instead, the Label stays empty.
EDIT:
The DataContext of my XAML (and thus, of the Label) is set to the ViewModel.
EDIT2: Of course, the real code is not as simple as described above. I built a minimal working example that only represents the above description:
XAML:
<Window x:Class="MyTestNamespace.MyXAML"
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">
<StackPanel>
<Label Content="{Binding Foo}"></Label>
<Label Content="{Binding Bar.Name}"></Label> <!-- Works fine! -->
</StackPanel>
</Window>
ViewModel:
namespace MyTestNamespace
{
class MyVM
{
public string Foo { get; set; }
public MyBar Bar { get; set; }
public MyVM()
{
Foo = "I am Foo.";
Bar = new MyBar("I am Bar's name.");
}
}
class MyBar
{
public string Name { get; set; }
public MyBar(string text)
{
Name = text;
}
}
}
This in fact DOES work as expected. Since I cannot share the actual code with you (too much and owned by company), I need to search for the cause on my own. Any hints on possible reasons are welcome!
Thanks to Vignesh N.'s comment I was able to solve the problem.
In the actual code Bar can change, but in the beginning it's name is an empty string. This is what the Label shows when the window is opened. Because the Label does not get notified when the Bar property changes, it does not update.
Solution: Make the ViewModel implement the INotifyPropertyChanged interface and define Bar like this:
private MyBar _bar;
public MyBar Bar
{
get
{
return _bar;
}
set
{
if (_bar != value)
{
_bar = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Bar)));
}
}
}
1.Your Model.cs:
public class Model : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
2.Your ViewModel:
public MainViewModel()
{
_model = new Model {Name = "Prop Name" };
}
private Model _model;
public Model Model
{
get
{
return _model;
}
set
{
_model = value;
}
}
3.Your View, with DataContext set to your ViewModel:
<Window x:Class="WpfApplication1.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"
mc:Ignorable="d"
Title="MainWindow"
DataContext="{StaticResource MainViewModel}">
<Grid>
<Label Content="{Binding Model.Name}"/>
</Grid>

How to bind in xaml to a textbox from a different class

I can figure out how to bind a property to a textbox in the codebehind, but with my current application I need to bind to a property from a different class. Here's a simplified version of what I have:
<Window x:Class="Project1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<TextBox x:Name="Textbox1" Text="{Binding Class1.Class2.TextToBind, Mode=TwoWay}" Height="20" Width="75" Background="#FFE5E5E5"/>
</Grid>
Codebehind:
namespace Project1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Class1 = new Class1();
}
public Class1 Class1 { get; set; }
}
}
Class1:
namespace Project1
{
public class Class1
{
public Class1()
{
Class2 = new Class2();
}
public Class2 Class2 { get; set; }
}
}
Final class:
namespace Project1
{
public class Class2
{
public Class2()
{
}
private string textToBind;
public string TextToBind { get { return textToBind; } set { SetProperty(ref textToBind, value); } }
public event PropertyChangedEventHandler PropertyChanged;
private void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = "")
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}
}
You have to set DataContext for your TextBox or for your Window
namespace Project1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Class1 = new Class1();
Class1.Class2.TextToBind = "Test";
this.DataContext = this;
}
public Class1 Class1 { get; set; }
}
}
Also you need to inherit Class2 from INotifyPropertyChanged:
public class Class2 : INotifyPropertyChanged
{
public Class2()
{
}
private string textToBind;
public string TextToBind { get { return textToBind; } set { SetProperty(ref textToBind, value); } }
public event PropertyChangedEventHandler PropertyChanged;
private void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = "")
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}
If you want to bind your textbox to a property from a class other than the datacontext of the window, you need to set it explicitly
I tried this code and it worked
<Window x:Class="Project1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
<!-- first add namespace of your project-->
xmlns:local="clr-namespace:Project1"
Title="Window1" Height="300" Width="300">
<!--second define your data context class as resource-->
<Window.Resources >
<local:Class2 x:Key="class2"></local:Class2>
</Window.Resources>
<Grid>
<TextBox x:Name="Textbox1" Text="{Binding TextToBind, Mode=TwoWay}" Height="20" Width="75" Background="#FFE5E5E5">
<!--third set the data context of the textbox Explicitly-->
<TextBox.DataContext>
<StaticResourceExtension ResourceKey="class2"/>
</TextBox.DataContext>
</TextBox>
</Grid>
</Window>
Please note : if you are going to set the property TextToBind programmatically and you want your UI to show the result, you have to implement INotifyPropertyChanged.

Metro UI not update

I'm just start working on metro app and i'm facing a problem that is dispatcher not updating the UI. My code is below please let me know what was the issue ?
public class Test : DependencyObject
{
public static readonly DependencyProperty CurrentItemProperty =
DependencyProperty.Register("NameOfPerson", typeof(string), typeof(Test), null);
public String NameOfPerson
{
get
{
return (string)GetValue(CurrentItemProperty);
}
set
{
runmethod(value);
}
}
public async void runmethod(String text)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
SetValue(CurrentItemProperty, text);
}
);
}
}
In main page i have an event button click which when fire update textbox.
private void Button_Click_2(object sender, RoutedEventArgs e)
{
Test t = new Test();
t.NameOfPerson = "Hello Umar";
}
MainPage.xaml look like this
<Page
x:Class="TestApplication.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestApplication"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Button Content="Button" HorizontalAlignment="Left" Margin="207,187,0,0" VerticalAlignment="Top" Height="80" Width="255" Click="Button_Click_2"/>
<TextBox x:Name="textB" Text="{Binding NameOfPerson}" HorizontalAlignment="Left" Height="80" Margin="730,187,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="307"/>
</Grid>
</Page>
If you are what you are trying to do is having a button refresh your Text, you should look into the MVVM pattern and have the Binding update your UI.
To do this you'll have to create your Object, in this case, let's say a person.
public class Person
{
public string Name { get; set; }
}
Secondly you would want to have a person inside a viewmodel that you'll update using your button. The viewmodel will derive from BindableBase which is a part of Windows Store applications if you would use such thing as Basic Page. The Viewmodel looks like this:
public class MainPageViewModel : BindableBase
{
public MainPageViewModel()
{
}
private Person person;
public Person Person
{
get { return person; }
set { SetProperty(ref person, value); }
}
public void LoadData()
{
Person = new Person() { Name = "Simple name" };
}
public void UpdatePerson()
{
Person.Name = "Updated Name";
OnPropertyChanged("Person");
}
}
and in case you dont have the bindableBase, it looks like this:
[Windows.Foundation.Metadata.WebHostHidden]
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
{
if (object.Equals(storage, value)) return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
On your MainPage you create the ViewModel and set the DataContext on your Page. Also you would want to handle your object inside your Viewmodel, so you'll create a update method when clicking the button that will modify your Person object:
public sealed partial class MainPage : Page
{
private readonly MainPageViewModel viewModel;
public MainPage()
{
this.InitializeComponent();
viewModel = new MainPageViewModel();
viewModel.LoadData();
this.DataContext = viewModel;
}
private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
viewModel.UpdatePerson();
}
}
And finally your TextBox in the UI to point at the Person's name property inside the Viewmodel:
<TextBox
x:Name="textB"
Text="{Binding Person.Name}"
HorizontalAlignment="Left"
Height="80"
Margin="730,187,0,0"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="307" />
I hope this fulfills your question on how you can have a button updating your UI.

How do you perform Binding with a DataGridView in WPF?

I want to bind a datagrid view in a user control that is docking to a main WPF form. However everytime I try to bind the data it must pre exist and won't update. Is there a way to perform this in the XAML directly to know when an event is triggered to update the datagridview rather than do it in the code behind?
Partial code of XAML:
xmlns:c="clr-namespace:TestWPFMain"
<UserControl.Resources>
<c:GridData x:Key="dataforGrid"/>
</UserControl.Resources>
<Grid>
<DataGrid Grid.Row="2" x:Name="datagridMain" ItemsSource="{Binding Source={StaticResource dataforGrid}, Path=Results, Mode=TwoWay}" />
</Grid>
Code Behind for UserControl above:
public GridControl()
{
InitializeComponent();
GridData gd = new GridData();
gd.UpdateResults();
//datagridMain.ItemsSource = gd.Results;
-- This code above will work if I uncomment but I want it to be bound
directly and was curious as I thought the mode of 'two way' would
do this. I am not certain and most examples assume property is already
set up and not being created and updated.
}
Code Class for GridData:
class PersonName
{
public string Name { get; set; }
}
class GridData
{
public ObservableCollection<PersonName> Results { get; set; }
public void UpdateResults()
{
using (EntityDataModel be = new EntityDataModel())
{
var list = be.tePersons.Select(x => new PersonName { Name = x.FirstName });
Results = new ObservableCollection<PersonName>(list);
}
}
}
To use binding like this, you need to:
Set the DataContext correctly on the DataGrid (or on one of its parent)
Implement INotifyPropertyChanged on your model class, and raise PropertyChanged in the property setter.
1)
Set your window's DataContext to the GridData object:
public GridControl()
{
InitializeComponent();
GridData gd = new GridData();
gd.UpdateResults();
this.DataContext = gd;
}
2)
Implement INotifyPropertyChanged. This ensures that your view gets notified when the Results property gets updated:
public class GridData : INotifyPropertyChanged
{
private ObservableCollection<PersonName> _results;
public ObservableCollection<PersonName> Results
{
get { return _results; }
set
{
_results = value;
RaisePropertyChanged("GridData");
}
}
// ...
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string prop)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
#endregion
}
Then you can simply bind to the path relative to the data context.
<DataGrid ItemsSource="{Binding Results}" />
Note that you don't need two-way binding in this case -- that's for propagating changes from the View back to your model (ie, most useful for when there's a UI control like a text box or checkbox).
Here is an example (I used Window, but it will work the same for UserControl)
Xaml:
<Window x:Class="WpfApplication4.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" Name="UI">
<Grid>
<DataGrid Grid.Row="2" x:Name="datagridMain" ItemsSource="{Binding ElementName=UI, Path=GridData.Results, Mode=TwoWay}" />
</Grid>
</Window>
or id you want the whole DataContext:
<Window x:Class="WpfApplication4.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" Name="UI">
<Grid>
<DataGrid Grid.Row="2" x:Name="datagridMain" DataContext="{Binding ElementName=UI, Path=GridData}" ItemsSource="{Binding Results}" />
</Grid>
</Window>
Code:
You will have to implement INotifyPropertyChanged so the xaml knows GridData has changed
The ObservableCollection inside GridData as this function built-in so anytime you add remove items they will update the DataGrid control
public partial class MainWindow : Window , INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
GridData = new GridData { Results = new ObservableCollection<PersonName>() };
GridData.Results.Add(new PersonName { Name = "Test1" });
GridData.Results.Add(new PersonName { Name = "Test2" });
}
private GridData _gridData;
public GridData GridData
{
get { return _gridData; }
set { _gridData = value; NotifyPropertyChanged("GridData"); }
}
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Notifies the property changed.
/// </summary>
/// <param name="info">The info.</param>
public void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
Classes:
I made a small change to the update method, so it just clears and updates the existing ObservableCollection, otherwise you would have to Implement INotifypropertyChanged to this class if you assign a new ObservableCollection.
public class PersonName
{
public string Name { get; set; }
}
public class GridData
{
public GridData()
{
Results = new ObservableCollection<PersonName>()
}
public ObservableCollection<PersonName> Results { get; set; }
public void UpdateResults()
{
using (EntityDataModel be = new EntityDataModel())
{
// Just update existing list, instead of creating a new one.
Results.Clear();
be.tePersons.Select(x => new PersonName { Name = x.FirstName }).ToList().ForEach(item => Results.Add(item);
}
}
}

Categories