OnPropertyChanged wont change when used wth observable collection and single property - wpf

Loads the dataGrid and populates the Datagrid a row of 1'
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
update();
//this.DataContext = this;
}
CricketEvent events = new CricketEvent();
private void update()
{
events.updateList(new CricketEvent[1] { new CricketEvent(){Runs="1"} });
DG1.ItemsSource = events.RunsList;
}
private void DG1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
Window1 windowToOpen = new Window1();
var selectedUser = this.DG1.SelectedItem;
windowToOpen.Show();
}
}
Main class that loads the OnPropertyChanged I have a List property and string property that calls the OnPropertyChanged but I want the individual "Runs" property to be updated on its own rather than the whole collection.
class CricketEvent : INotifyPropertyChanged
{
private ObservableCollection<CricketEvent> runsList;
public string runs { get; set; }
public CricketEvent(string numofRuns) {
this.Runs = numofRuns;
}
public CricketEvent() { }
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<CricketEvent> RunsList
{
get { return this.runsList; }
set
{
if (value != this.runsList)
{
this.runsList = value;
OnPropertyChanged("RunsList");
}
}
}
public string Runs
{
get { return runs; }
set
{
runs = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("Runs");
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public ObservableCollection<CricketEvent> updateList(CricketEvent []events)
{
runsList = new ObservableCollection<CricketEvent>(events.ToList());
return runsList;
}
}
This is the update window that brings up a text box and should change the "1s" In the previous window to whatever is typed into the textbox
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
CricketEvent events = new CricketEvent();
MainWindow main = new MainWindow();
private void Button_Click(object sender, RoutedEventArgs e)
{
events.updateList(new CricketEvent[1] { new CricketEvent(txt1.Text.ToString()) });
main.DG1.ItemsSource = events.RunsList;
}

The Button_Click event in Window1 does not use the instance of MainWindow that is show - it creates a new Window instance (that is not shown) and adds the updated list to the DG1.ItemsSource property. To solve that, pass the original instance of Window to the created Window1 in constructor and use that.
However, you should review your update strategy (and code style) because there is potential for improvments:
It is not a good idea to create a new collection if you want to update just one property of one item. Observable collections provide change notification, so you dont have to recreate the collection at all.
Instead of assinging the collection in code behind, use databinding to bind the collection to the ItemsSource. DataBinding results in automatic update of GUI elements if the collection or one item of you collection changed.

Related

Reload Json content in MVVM and WPF

I have a Model called FieldModel. In ViewModel I am setting its properties through a json file parsing like this:
foreach (var field in innerClass.Item2.Properties)
{
FieldView fieldView = new FieldView(field);
fieldView.ClassName = classView.ClassName;
fieldView.IsAbstract = classView.IsAbstract;
FieldViewItems.Add(fieldView);
}
My question is: how to make the binding properly with the reload button in order to reload the content of json file when it's being modified ?
First implement a Command class, I prefer something like this :
public class GeneralCommand : ICommand
{
private Action ToBeExecutedAction;
private Func<bool> ExecutionValidatorFunc;
public GeneralCommand(Action toBeExecutedAction, Func<bool> executionValidatorFunc)
{
ToBeExecutedAction = toBeExecutedAction;
ExecutionValidatorFunc = executionValidatorFunc;
}
public bool CanExecute(object parameter)
{
return ExecutionValidatorFunc();
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
ToBeExecutedAction();
}
}
Now inside your ViewModel class, implement something like the following :
public class FieldModel : INotifyPropertyChanged
{
private GeneralCommand _generalCommand;
public FieldModel()
{
Action action = new Action(ChangeValue);
_generalCommand = new GeneralCommand(action, new Func<bool>(() => true));
}
public ICommand ReloadValues
{
get
{
return _generalCommand;
}
}
string _jsonText;
public string JsonText
{
get
{
return _jsonText;
}
}
private void ChangeValue()
{
//Change JsonText here
//Then raise event change to be updated
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("TextJson"));//Here fill property name
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Then from the Xaml bind your Reload button into command property ReloadValues inside your ViewModel object, and bind the JsonText property with a WPF control for example a Textbox.
Hope this is useful.

ObservableCollection gets reset (item count 0) going between 2 views

I am very new to MVVM so hopefully this isnt a hard problem.
Basically I have two Views:-
1. Holds a Data Grid which displays everything inside the ObservableCollection object
2. The second view basically has two text boxes which adds to the ObservableCollection when the user presses OK on the form.
Bascially what I am doing is showing the 2nd view from the 1st view with a button click, button labelled "Add Project"
Then I enter the information I need to add to the ObservableCollection in the 2nd view. When I press OK on the form, It calls a method "AddMProduct" which basically adds a item to the collection inside the ViewModel.
But the problem is by doing this its creating a new ViewModel() object so therefore reinitialise the ObservableCollection. So therefore the collection gets reset back to zero.
So in the MVVM model, how do I basically retain the collection, between the 2 views and the ViewModel?
Thanks
------------------Code---------------
VIEW 1
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnAddProjectGroup_Click(object sender, RoutedEventArgs e)
{
// Open new window here to add a new project group
AddProductGroup dlg = new AddProductGroup();
dlg.ShowDialog();
}
}
VIEW 2
ProductGroupBindable newProduct = new ProductGroupBindable();
ProductsViewModel viewModel = null;
public AddProductGroup()
{
viewModel = new ProductsViewModel();
InitializeComponent();
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
newProduct.Id = System.Guid.NewGuid();
newProduct.Name = txtName.Text;
newProduct.Description = txtDescription.Text;
viewModel.AddProduct(newProduct);
this.Close();
}
VIEWMODEL
class ProductsViewModel : INotifyPropertyChanged
{
private ObservableCollection<ProductGroupBindable> m_ProductCollection;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public ObservableCollection<ProductGroupBindable> ProductCollection
{
get
{
Test();
return m_ProductCollection;
}
set
{
m_ProductCollection = value;
}
}
private void Test()
{
m_ProductCollection.Add(new ProductGroupBindable { Description = "etc", Name = "test12" });
}
public ProductsViewModel()
{
if (m_ProductCollection == null)
ProductCollection = new ObservableCollection<ProductGroupBindable>();
}
public void AddProduct(ProductGroupBindable newProduct)
{
ProductCollection.Add(newProduct);
NotifyPropertyChanged("ProductCollection");
}
Consider this simple option to fix the problem. Create an overload constructor of the dialog view that accepts ProductsViewModel as parameter. With that you can pass existing viewmodel object from MainWindow to the dialog, hence avoid instantiating new empty viewmodel :
//in MainWindow
private void btnAddProjectGroup_Click(object sender, RoutedEventArgs e)
{
//Open new window here to add a new project group
AddProductGroup dlg = new AddProductGroup(this.viewmodel);
dlg.ShowDialog();
}
//in AddProductGroup :
public AddProductGroup(ProductsViewModel vm)
{
viewModel = vm;
InitializeComponent();
}

change main form controls by trigger event inside canvas

I am currently working on a project that required me to use a canvas in order to draw rectangles around specific places in a picture (to mark places)
Each rectangle (actually "rectangle" since it is also a custom class that I created by inheriting from the Grid class and contain a rectangle object) contains properties and data about the marked place inside the picture.
my main form contains controls such as TextBox ,DropDownLists and etc.
Now what I am trying to do is that for each time I am clicking on the "rectangle" object the main form controls will be filled with the object data.
I do not have access to those controls from the canvas class.
this code is inside the costume canvas class to add the object into the canvas:
protected override void OnMouseLeftButtonDown( MouseButtonEventArgs e)
{
if(e.ClickCount==2)
{
testTi = new TiTest();
base.OnMouseLeftButtonDown(e);
startPoint = e.GetPosition(this);
testTi.MouseLeftButtonDown += testTi_MouseLeftButtonDown;
Canvas.SetLeft(testTi, e.GetPosition(this).X);
Canvas.SetTop(testTi, e.GetPosition(this).X);
this.Children.Add(testTi);
}
}
and by clicking an object that is placed inside the canvas i want to get the information.
for now just want to make sure i am getting the right object with a simple messagebox
void testTi_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show(sender.GetType().ToString());
}
this is my costume "Rectangle" class
class TiTest:Grid
{
private Label tiNameLabel;
private Rectangle tiRectangle;
private String SomeText = string.Empty;
private String version = "1.0";
private String application = "CRM";
private String CRID = "NNN";
public String SomeText1
{
get { return SomeText; }
set { SomeText = value; }
}
public Rectangle TiRectangle
{
get { return tiRectangle; }
set { tiRectangle = value; }
}
public Label TiNameLabel
{
get { return tiNameLabel; }
set { tiNameLabel = value; }
}
public TiTest()
{
this.SomeText = "Hello World!!";
this.TiNameLabel = new Label
{
Content = "Test Item",
VerticalAlignment = System.Windows.VerticalAlignment.Top,
HorizontalAlignment = System.Windows.HorizontalAlignment.Left
};
TiRectangle = new Rectangle
{
Stroke = Brushes.Red,
StrokeDashArray = new DoubleCollection() { 3 },//Brushes.LightBlue,
StrokeThickness = 2,
Cursor = Cursors.Hand,
Fill = new SolidColorBrush(Color.FromArgb(0, 0, 111, 0))
};
Background= Brushes.Aqua;
Opacity = 0.5;
this.Children.Add(this.tiNameLabel);
this.Children.Add(this.tiRectangle);
}
}
is there any way to access the main form controls from the costume canvas class or by the costume rectangle class?
Thanks in advance
You can have your main window be binded to a singletone ViewModel holding the properties of the rectangles.
ViewModel
public class MainWindowViewModel : INotifyPropertyChanged
{
#region Singletone
private static MainWindowViewModel _instance;
private MainWindowViewModel()
{
}
public static MainWindowViewModel Instance
{
get
{
if (_instance == null)
_instance = new MainWindowViewModel();
return _instance;
}
}
#endregion
#region Properties
private string _someInfo;
public string SomeInfo
{
get
{
return _someInfo;
}
set
{
if (_someInfo != value)
{
_someInfo = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("SomeInfo"));
}
}
}
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
In main window xaml
<TextBox Text="{Binding SomeInfo}"/>
Also set the view model as your main window data context (in main window constructor for exmaple)
this.DataContext = MainWindowViewModel.Instance;
Finally, from where you handle the click event of the rectangles (testTi_MouseLeftButtonDown), access the MainWindowViewModel instance and set it's properties accordingly.
MainWindowViewModel.Instance.SomeInfo = myRectangle.SomeInfo;
This will trigger the PropertyChanged event, which will update your control's on the main window.
If you are not familiar with the MVVM (Model, View. View Model) pattern you can read about it here
Hope this helps

MVVM pattern filter listview and update on new item

I've been struggling with this problem for a couple of days, but somewhere I obviously on a wrong track. Situation is as follows: I have a window with 3 buttons (Add New Task, Show Inbox, Show Today) and a Listview. My TaskViewModel class is has a ObservableCollection of TaskModel, with pretty simple Filter functionality. My class looks as follows:
public class TaskViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public ObservableCollection<TaskModel> TaskCollection { get; private set; }
public TaskViewModel()
{
TaskDataAccess ac = new TaskDataAccess();
this.TaskCollection = ac.GetAllTasks();
}
public ICommand AddTaskCommand
{
get { return new DelegateCommand(this.AddTask); }
}
public ICommand FilterInboxCommand
{
get { return new DelegateCommand(this.FilterInbox); }
}
public void AddTask()
{
this.TaskCollection.Add(new TaskModel(9, "I", "New Item for testing"));
this.GetListCollectionView().Filter = this.IsInbox; ;
}
private void FilterInbox()
{
this.GetListCollectionView().Filter = this.IsInbox;
}
....
}
The filter functionality works fine, but when I call the new window "Add new task" it does not update the listview (here: this.TaskCollection.Add(new TaskModel(9, "I", "New Item for testing"));
I'd appreciate if someone could give me a hint...
Try to do this...
create a private field (say _taskCollection) to backup your property TaskCollection.
private readonly ObservableCollection<TaskModel> _taskCollection;
Then remove the private setter from TaskCollection property. Also remove the constructor code that loads the collection.
Instead write your getter this way...
public ObservableCollection<TaskModel> TaskCollection {
get {
if (this._taskCollection == null)
{
TaskDataAccess ac = new TaskDataAccess();
this._taskCollection = ac.GetAllTasks();
}
return this._taskCollection;
}
}
Let me know if this way works ....

Silverlight: INotifyPropertyChanged does not seem to work

I haven't implement this pattern for a while (and when I did it was in 2, as opposed to 3), and I have several examples that all seem straight forward, but I can't work out what I have done wrong in the below piece of code (The Items are not updated when the property event fires):
public partial class Index : Page
{
private IndexViewModel _vm;
public Index()
{
InitializeComponent();
_vm = new IndexViewModel(19);
this.TheDataGrid.ItemsSource = _vm.Rows;
}
public class IndexViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
this.PropertyChanged(this, e);
}
public SortableCollectionView Rows
{
get
{
return _rows;
}
set
{
if (_rows == value)
return;
_rows = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Rows"));
}
}
This does not refresh my datagrid... as a 'hack' I have had to pass the datagrid object into my viewmodel and bind it there:
public IndexViewModel(int containerModelId, DataGrid shouldNotNeed)
{
ContainerModelId = containerModelId;
LoadOperation<vwColumn> headings = _ttasContext.Load(_ttasContext.GetRecordColumnsQuery(ContainerModelId));
headings.Completed += (sender2, e2) =>
{
//load data
LoadOperation<vwDataValue> data = _ttasContext.Load(_ttasContext.GetRecordsQuery(ContainerModelId, null));
data.Completed += (sender3, e3) =>
{
Rows = FormatData(data, headings);
shouldNotNeed.ItemsSource = Rows;
};
};
}
Assigning _vm.Rows to TheDataGrid.ItemsSource does not wire any change notification callback automatically. Try this:
in xaml:
<... x:Name=TheDataGrid ItemsSource={Binding Rows}>
In code:
this.DataContext = _vm;
As Codism points out your main problem is you need to use binding to take advantage of an INotifyPropertyChanged. However I would recommend this implementation pattern:-
public event PropertyChangedEventHandler PropertyChanged;
void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name);
}
...
set
{
if (_rows != value)
{
_rows = value;
NotifyPropertyChanged("Rows");
}
}
Note that this approach minimises the impact on a an object instance whose properties are not being observed. In the original pattern you create instances of PropertyChangedEventArgs and calls to the event delegate going off regardless of whether anything is actually listening.
this.TheDataGrid.ItemsSource = _vm.Rows
When a collection is assigned as the ItemsSource of a DataGird , any changes made to the collection can be observed by the DataGrid if the source implements INotifyCollectionChanged.
From your code sample , I can't tell if the type SortableCollectionView implements INotifyCollectionChanged or inherits from ObservableCollection.
Implementing INotifyCollectionChanged would mean that you can't reset the backing field _rows for property Rows , you can clear items in the collection and add them as needed.
Hope this helps

Resources