Winforms Databinding Notification - c#

My model is mainly made from the 2 classes below (I actually got another class which inherits from the abstract class but it doesnt matter I think):
public abstract class FeedForEvents: BaseObservableObject
{
public abstract void ReadFeed();
public List<Event> Events { get; set; }
public void AddEvent(Event aEvent)
{
Events.Add(aEvent);
OnPropertyChanged("Events");
}
}
public class Event : BaseObservableObject
{
public string MyProp
{
get
{
return _myProp;
}
set
{
_myprop= value;
OnPropertyChanged();
}
}
}
My form contains:
private BindingList<FeedForEvents> ListFeedsForEvents = new BindingList<FeedForEvents>();
private BindingList<Event> ListEvents
=> new BindingList<Event>(ListFeedsForEvents.SelectMany(m =>m.Events).ToList());
private BindingSource pagesBindingSource = new BindingSource();
public void RefreshGrid()
{
pagesBindingSource.DataSource = ListEvents;
this.grdEvents.DataSource = pagesBindingSource;
this.grdEvents.AutoGenerateColumns = true;
}
But even if my 2 objects correctly raised the PropertyChanged notficiation, the interface never show the objects updated (unless I manually refresh them by pressing a button to manually call RefreshGrid() ). Why?

Related

Set a Property in a ViewModel from Another ViewModel

I am trying to pass a value to a view model from another view model before navigating to the page attached to that view model.
I was previously passing it to the view, then passing it to the view model. This seems like a clumsy way of doing things.
I am not using any kind of framework so that is not an option.
At the moment the property is set as static and this works but im not sure if this is good practice.
The code:
View model 1:
This command opens the new page:
public void OpenRouteDetails()
{
RouteStopPopOverViewModel.RouteName = "TestRoute";
App.Page.Navigation.PushAsync(new RouteStopPopOverView());
}
View model 2: (RouteStopPopOverViewModel)
public static string RouteName { get; set; }
This does work but I would prefer not to use static as a way to achieve this.
Is there some way to set the RouteName property without using static or passing it through view-> view model.
I have seen some answers about this but they don't seem to answer to question clearly.
Share a controller class between view models.
The same instance has to be supplied to the constructor in both view models.
So you can set values, and listen for events in both view models.
The controller class becomes the intermediary.
public class SharedController : IControlSomething
{
private string _sharedValue;
public string SharedValue
{
get => _sharedValue;
set
{
if (_sharedValue == value)
return;
_sharedValue = value;
OnSharedValueUpdated();
}
}
public event EventHandler SharedValueUpdated;
protected virtual void OnSharedValueUpdated()
{
SharedValueUpdated?.Invoke(this, EventArgs.Empty);
}
}
public class ViewModel1
{
private readonly IControlSomething _controller;
public ViewModel1(IControlSomething controller)
{
// Save to access controller values in commands
_controller = controller;
_controller.SharedValueUpdated += (sender, args) =>
{
// Handle value update event
};
}
}
public class ViewModel2
{
private readonly IControlSomething _controller;
public ViewModel2(IControlSomething controller)
{
// Save to access controller values in commands
_controller = controller;
_controller.SharedValueUpdated += (sender, args) =>
{
// Handle value update event
};
}
}
here the sample you can achieve your requirement easily with navigation
public class ViewModelFrom : BaseViewModel
{
async Task ExecuteCommand()
{
string routeName="value to trasfer";
Navigation.PushAsync(new View(routeName));
}
}
public partial class View : ContentPage
{
public View(string routeName)
{
InitializeComponent();
BindingContext = new ViewModelTo(routeName);
}
}
public class ViewModelTo : BaseViewModel
{
public string RouteName { get; set; }
public ViewModelTo(string routeName)
{
RouteName=routeName;
}
}
If there is a hierarchy you could express that in a parent to both of them.
public class Route
{
private string Name;
}
public class RouteSelectedArgs : EventArgs
{
public Route Selected { get; set; }
}
public interface IRouteSelection
{
event EventHandler<RouteSelectedArgs> RouteSelected;
}
public interface IRouteDetails { }
public class RouteWizard
{
public UserControl view { get; set; }
private IRouteSelection _selection;
private IRouteDetails _details;
public RouteWizard(IRouteSelection selection, IRouteDetails details)
{
_selection = selection;
_details = details;
_selection.RouteSelected += Selection_RouteSelected;
view = MakeView(_selection);
}
private void Selection_RouteSelected(object sender, RouteSelectedArgs e)
{
_selection.RouteSelected -= Selection_RouteSelected;
view = MakeView(_details, e.Selected);
}
private UserControl MakeView(params object[] args)
{
////magic
throw new NotImplementedException();
}
}
As you are using the MVVM pattern, you can use one of the many MVVM Frameworks to achieve this.
I use FreshMvvm and it allow me to pass parameters between view models like this
await CoreMethods.PushPageModel<SecondPageModel>(myParameter, false);
Then in SecondPageModel I can see access the parameters in the Init method
private MyParamType _myParameter;
public override void Init(object initData)
{
base.Init(initData);
var param = initData as MyParamType;
if (param != null)
{
_myParameter = param;
}
}
You can find more details about FreshMvvm here although most MVVM frameworks have similar functionality.

Grid binded to EntityFramework Poco class via BindingSource is not automatically refreshing

This one is test project to show my question. (VS2012, WinForms, EntityFramework 5, XtraGrid 12.5)
Model created by EF PowerTools - Reverse Engineer CodeFirst tool.
In the timer1_tick event i'm changing mypoco.value property. I'm expecting that grid.cell shows this changes automatically but not. I also tried with textbox but the same.
if i uncomment BindingSource.ResetCurrentItem() in timer1_tick works expected but this is not my question. If i force to grid (or Textbox) to refresh everything is fine.
I expect that ef created proxy object notifies DbSet.Local (ObservableCollection) -> BindingList -> BindingSource -> Grid etc via interfaces,methots or inherit or i don't know... I'm asking about this notifying system and why not working? Or it is working but my expectation is wrong? (
Why this is not working as expected, Where i'm failing? Please also read notes in the code.
Thank you.
//FORM CODE
public partial class Form1 : Form
{
testContext context = new testContext();
MyPOCO mypoco;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
mypoco = context.MyPOCOes.Create();
// mypoco is created but not proxied currently. state = detached
// After adding it context proxy created and change tacking will be available
context.MyPOCOes.Add(mypoco);
// mypoco is in the memory but not saved to database. This is why using Local
myPOCOBindingSource.DataSource = context.MyPOCOes.Local.ToBindingList();
// Setup timer
timer1.Interval = 15 * 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
// Change the property and then warn user about this event occured
// At this point mypoco is proxied
mypoco.Value = 99;
this.Text = "Timer Tick";
//myPOCOBindingSource.ResetCurrentItem();
}
}
// some code from Form1.Designer file
private System.Windows.Forms.BindingSource myPOCOBindingSource;
private void InitializeComponent()
{
this.myPOCOBindingSource = new System.Windows.Forms.BindingSource();
....
this.myPOCOGridControl.DataSource = this.myPOCOBindingSource;
}
//MYPOCO
public partial class MyPOCO
{
public int ID { get; set; }
public Nullable<int> Value { get; set; }
}
//MAPPING
public class MyPOCOMap : EntityTypeConfiguration<MyPOCO>
{
public MyPOCOMap()
{
// Primary Key
this.HasKey(t => t.ID);
// Table & Column Mappings
this.ToTable("MyPOCO");
this.Property(t => t.ID).HasColumnName("ID");
this.Property(t => t.Value).HasColumnName("Value");
}
}
//CONTEXT
public partial class testContext : DbContext
{
static testContext()
{
Database.SetInitializer<testContext>(null);
}
public testContext()
: base("Name=testContext")
{
}
public DbSet<MyPOCO> MyPOCOes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new MyPOCOMap());
}
}
The proxy code of MyPoco is here: Nothing related on bindings (of course) ...
public sealed class MyPOCO_F874E881B0FD3EF02199CD96C63396B451E275C5116C5DFBE892C68733857FDE : MyPOCO, IEntityWithChangeTracker, IEntityWithRelationships
{
[NonSerialized]
private IEntityChangeTracker _changeTracker;
private static Func<object, object, bool> _compareByteArrays;
[NonSerialized, IgnoreDataMember, XmlIgnore, ScriptIgnore]
public object _entityWrapper;
private System.Data.Objects.DataClasses.RelationshipManager _relationshipManager;
private static Action<object> _resetFKSetterFlag;
private void EntityMemberChanged(string text1)
{
if (this._changeTracker != null)
{
this._changeTracker.EntityMemberChanged(text1);
}
}
private void EntityMemberChanging(string text1)
{
if (this._changeTracker != null)
{
this._changeTracker.EntityMemberChanging(text1);
}
}
public void SetChangeTracker(IEntityChangeTracker tracker1)
{
this._changeTracker = tracker1;
}
public override int ID
{
get
{
return base.ID;
}
set
{
if (base.ID != value)
{
try
{
this.EntityMemberChanging("ID");
base.ID = value;
this.EntityMemberChanged("ID");
}
finally
{
_resetFKSetterFlag(this);
}
}
}
}
public System.Data.Objects.DataClasses.RelationshipManager RelationshipManager
{
get
{
if (this._relationshipManager == null)
{
this._relationshipManager = System.Data.Objects.DataClasses.RelationshipManager.Create(this);
}
return this._relationshipManager;
}
}
public override int? Value
{
get
{
return base.Value;
}
set
{
try
{
this.EntityMemberChanging("Value");
base.Value = value;
this.EntityMemberChanged("Value");
}
finally
{
_resetFKSetterFlag(this);
}
}
}
}

How to make c# classes aware of each other?

I have two classes that inherit from the same abstract class. I want both of them or at least one to be aware of changes in a specific property of the other. Is there any simple method for doing this? I've been trying to move the variable to the parent class, but that just creates 2 of the same variable, and when I create a reference to the other class inside the first one the same thing happens. thanks.
This is what my code looks like:
public abstract class Animal
{
public int MovementSpeed;
public bool Death;
public string Feedback;
public bool DeerCaught;
public int tiredRate;
public virtual int Movement()
{
MovementSpeed = MovementSpeed - tiredRate;
return MovementSpeed;
}
public virtual string Print()
{
return Feedback;
}
}
public class Deer : Animal
{
public string hidden;
public string Foraging;
public int DeerCount;
public Deer()
{
this.DeerCount = 10;
this.DeerCaught = false;
this.MovementSpeed = 10;
this.tiredRate = 2;
}
public void Hide()
{
if (Hunting)
{
Feedback = "The deer is hiding.";
if (DeerCount > 0)
{
Print();
}
}
else
{
//Forage();
}
}
public void Forage()
{
if (!Hunting)
{
Feedback = "The deer is searching for food.";
if (DeerCount > 0)
{
Print();
}
}
else
{
//Hide();
}
}
}
public class Wolf : Animal
{
public int Hunger;
public bool Hunting;
public Wolf()
{
this.Hunting = false;
this.Hunger = 10;
this.MovementSpeed = 10;
this.tiredRate = 1;
}
public bool Hunt()
{
if (Hunger < 5)
{
Hunting = true;
Feedback = "The wolf is searching for his next meal.";
if (DeerCaught == true)
{
Hunger++;
}
else
{
Hunger--;
}
return Hunting;
}
else
{
Hunting = false;
Feedback = "The wolf decides to rest.";
Hunger--;
return Hunting;
}
}
public void Die()
{
if (Hunger < 0)
{
Death = true;
Feedback = "The wolf has lost the hunt.";
}
}
}
I've tried setting Hunting as static in the base class, but I just end up getting two different versions of 'Hunting' when I run the methods of each class.
If this is intended as a simulation, then Deer isn't told when a wolf is hunting, it has to find out. The analogue here is to have some way that the Deer can query about the presence of wolves (something like Deer.LookForWolves(), then to check the value of the Hunting property on each wolf. This will require some sort of controller class, representing the world.
class World
{
public static List<Animal> Animals = new List<Animal>();
//...
}
class Deer : Animal
{
//...
bool IsSafe()
{
return LookForWolves().All(wolf => !wolf.Hunting);
}
List<Wolf> LookForWolves()
{
return World.Animals.OfType<Wolf>();
}
//...
Alternatively, you could reference World as a member of each Animal, passed in via the constructor. It's up to you, and will depend on whether you need to have multiple World objects, each with a different list of Animals.
Something like implementing INotifyPropertyChanged could help:
First, declare some classes that implement INotifyPropertyChanged:
abstract class Base {
}
class ClassA : Base, INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private string _property;
public string ClassAProperty {
get {
return _property;
}
set {
_property = value;
PropertyChanged(this, new PropertyChangedEventArgs("ClassAProperty"));
}
}
}
class ClassB : Base, INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private string _property;
public string ClassBProperty {
get {
return _property;
}
set {
_property = value;
PropertyChanged(this, new PropertyChangedEventArgs("ClassBProperty"));
}
}
}
Then, wire up new instances to subscribe to the PropertyChanged event:
using System.ComponentModel;
static void Main(string[] args) {
ClassA a = new ClassA();
a.PropertyChanged += PropertyChanged;
a.ClassAProperty = "Default value";
ClassB b = new ClassB();
b.PropertyChanged += PropertyChanged;
b.ClassBProperty = "Default value";
b.ClassBProperty = "new value in B";
a.ClassAProperty = "new value in A";
Console.Read();
}
static void PropertyChanged(object sender, PropertyChangedEventArgs e) {
Console.WriteLine("Property {0} on object {1} was changed, the value is \"{2}\"", e.PropertyName, sender.GetType().Name, sender.GetType().GetProperty(e.PropertyName).GetValue(sender));
}
Output of this is:
Property ClassAProperty on object ClassA was changed, the value is "Default value"
Property ClassBProperty on object ClassB was changed, the value is "Default value"
Property ClassBProperty on object ClassB was changed, the value is "new value in B"
Property ClassAProperty on object ClassA was changed, the value is "new value in A"
Each time either property is set, PropertyChanged is called, which in the above example writes the details to the console.
In your use case, you would have the event call a method in the other class (if I understand you correctly).
A very basic way to notify property changed with your own delegate definition. Since you do not provide any code I made up some classes myself. Use this as an example to modify your own code:
public delegate void PropertyChangedEventHandler();
public abstract class Base
{
}
public class A : Base
{
public event PropertyChangedEventHandler PropertyChanged;
private int _value;
public int Value
{
get { return _value; }
set
{
_value = value;
if (PropertyChanged != null)
{
PropertyChanged();
}
}
}
public class B : Base
{
private A _a;
public B(A a)
{
_a = a;
a.PropertyChanged += new PropertyChangedEventHandler(a_PropertyChanged);
}
private void a_PropertyChanged()
{
Console.WriteLine(_a.Value);
}
}
public class Application()
{
public void DoStuff()
{
var a = new A();
var b = new B(a);
}
}
The basic idea is to pass a reference of one object to the other. For example tell the deer it is being hunted by the wolf:
public class Wolf : Animal
{
public void Hunt(Deer deer)
{
deer.SetHunter(this);
}
}
Now the deer can check whether a wolf is hunting it:
public class Deer : Animal
{
Wolf _hunter;
public void SetHunter(Wolf wolf)
{
_hunter = wolf;
}
public void Hide()
{
if (_hunter != null)
{
Feedback = "The deer is hiding.";
}
else
{
//Forage();
}
}
}
This can be improved to be more generic, but it's the basic idea of passing a reference of one object to the other.
Don't use public fields for the properties of your classes. This way you will never be aware of changes and therefore can not notify others. Put the public fields into properties and always use these properties to change the value even from inside the Animal class. The property setter can then be used to notify others of changes.
public abstract class Animal
{
private int _movementSpeed;
public int MovementSpeed
{
get
{
return _movementSpeed;
}
set
{
if (_movementSpeed != value)
{
_movementSpeed = value;
OnMovementSpeedChanged();
}
}
}
protected virtual void OnMovementSpeedChanged()
{
// Derived classes can override this method.
// It will be called each time MovementSpeed changes.
}
public virtual int Movement()
{
// always use the property to change the value
// otherwise OnMovementSpeedChanged would never be called
MovementSpeed -= tiredRate;
return MovementSpeed;
}
}
Like others already mentioned you can also implement INotifyPropertyChanged in your base class. Since this uses events for notification not only derived classes can use that but also any other object that has a reference to an animal. The approach is basically the same. Each time the property value changes you call a method that fires the event. Any other object can then handle that event.
public abstract class Animal : INotifyPropertyChanged
{
private int _movementSpeed;
public int MovementSpeed
{
get
{
return _movementSpeed;
}
set
{
if (_movementSpeed != value)
{
_movementSpeed = value;
// call this method each time a property changes
OnPropertyChanged(new PropertyChangedEventArgs("MovementSpeed"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
{
// always implement events like this
// -> check if the event handler is not null, then fire it
if (PropertyChanged != null)
{
PropertyChanged(this, args);
}
}
}
A class that wants to handle the event can do it like so:
public class AnyClass
{
public AnyClass(Animal anAnimal)
{
TheAnimal = anAnimal;
anAnimal += Animal_PropertyChanged;
}
public Animal TheAnimal { get; private set; }
private void Animal_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "MovementSpeed")
{
Console.WriteLine("MovementSpeed changed");
}
}
}
Derived classes however don't need to handle the event. Since the OnPropertyChanged method is declared as protected virtual they can just override it.
public class Deer : Animal
{
protected override void OnPropertyChanged(PropertyChangedEventArgs args)
{
if (args.PropertyName == "MovementSpeed")
{
Console.WriteLine("MovementSpeed changed");
}
// don't forget to call the base class otherwise the event will never get fired
base.OnPropertyChanged(args);
}
}

Get/Set for a Private Static Collection?

I've defined a class with the following property:
private ObservableCollection<Job> allJobs;
Access is defined as follows:
public ObservableCollection<Job> AllJobs
{
get
{
return this.allJobs;
}
set
{
this.allJobs = value;
}
}
The get set works fine when I assign a whole ObservableCollection to the property, the set works fine for retrieving it obviously. But why have I lost all the methods that normally allow me to 'Add' (i.e. add 1 job to the collection)?
At the moment I'm having to create a temporary collection to populate to then assign to the allJobs property and I shouldn't have to.
Any ideas??
What do you mean with 'lost methods'? Have you tried AllJobs.Add()? The following code works for me:
void Main()
{
AllJobs = new ObservableCollection<Job>();
AllJobs.Add(new Job());
}
public class Job { }
private ObservableCollection<Job> allJobs;
public ObservableCollection<Job> AllJobs
{
get
{
return this.allJobs;
}
set
{
this.allJobs = value;
}
}
EDIT:
Based on your comment I've amended my code as follows but everything still works for me, I have noticed however that you don't seen to initialise the allJobs collection anywhere.
void Main()
{
PresentationManager.Instance.AllJobs.Add(new Job());
}
public class Job { }
sealed class PresentationManager
{
public static readonly PresentationManager Instance = new PresentationManager();
private PresentationManager()
{
allJobs = new ObservableCollection<Job>();
}
private ObservableCollection<Job> allJobs;
public ObservableCollection<Job> AllJobs
{
get { return this.allJobs; }
set { this.allJobs = value; }
}
}
Normally you wouldn't want a setter for such a property, as you would lose all events bound to the ObservableCollection when the setter is used.
public ObservableCollection<Job> AllJobs { get; private set; }

Silverlight Binding - Binds when item is added but doesn't get updates

I'm sorta at a loss to why this doesn't work considering I got it from working code, just added a new level of code, but here's what I have. Basically, when I bind the ViewModel to a list, the binding picks up when Items are added to a collection. However, if an update occurs to the item that is bound, it doesn't get updated. Basically, I have an ObservableCollection that contains a custom class with a string value. When that string value gets updated I need it to update the List.
Right now, when I debug, the list item does get updated correctly, but the UI doesn't reflect the change. If I set the bound item to a member variable and null it out then reset it to the right collection it will work, but not desired behavior.
Here is a mockup of the code, hopefully someone can tell me where I am wrong. Also, I've tried implementing INofityPropertyChanged at every level in the code below.
public class Class1
{
public string ItemName;
}
public class Class2
{
private Class2 _items;
private Class2() //Singleton
{
_items = new ObservableCollection<Class1>();
}
public ObservableCollection<Class1> Items
{
get { return _items; }
internal set
{
_items = value;
}
}
}
public class Class3
{
private Class2 _Class2Instnace;
private Class3()
{
_Class2Instnace = Class2.Instance;
}
public ObservableCollection<Class1> Items2
{
get {return _Class2Instnace.Items; }
}
}
public class MyViewModel : INofityPropertyChanged
{
private Class3 _myClass3;
private MyViewModel()
{
_myClass3 = new Class3();
}
private BindingItems
{
get { return _myClass3.Items2; } // Binds when adding items but not when a Class1.ItemName gets updated.
}
}
The answer to your question is that Class1 needs to implement INotifyPropertyChanged.
public class Class1 : INotifyPropertyChanged
{
private string _ItemName;
public string ItemName
{
get { return _ItemName; }
set
{
_ItemName = value;
NotifyPropertyChanged("ItemName");
}
}
private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
}

Categories

Resources