Home > OS >  Copy Clone with mvvm
Copy Clone with mvvm

Time:10-06

I need to create a wpf application with 2 buttons in a homework. one of the buttons is "copy" and the other is "clone". When i press the copy button, it should copy the information in the textboxes on the screen and create a new textbox and write it into it. When we press the clone button, it should copy the information in the same way and write it into a new textbox, but this time if I try to change the value in the cloned textboxes, it should change in all value in cloned textboxes. Does anyone know an example where I can learn the cloning part?

CodePudding user response:

OK, I was interested so I thought I give it a try and make a sample program myself. I can't give you my code to just copy, but here is some basic structure that worked for me:

View:

  • A ListBox with Textbox as Itemtemplate. ItemSource is bound to a ObservableCollection<StringModel> StringList in the ViewModel, which I will come to later. SelectedItem is Bound to a single StringModel SelectedString instance in the ViewModel
  • Clone Button
  • Copy Button
  • In the code behind (or wherever you want) simply set up your ViewModel as datacontext and the firing of the corresponding functions in the ViewModel, in case the buttons are pressed (next point)

StringModel This is as simple as it gets, a wrapper class around a string, in order to A) pass as reference and B) implement INotifyPropertyChanged. Notice the second constructer taking in a string as argument.

public class StringModel : ViewModelBase
{
    private string stringValue;

    public string StringValue
    {
        get { return stringValue; }
        set { SetProperty<string>(ref stringValue, value); }
    }


    public StringModel(){ }

    public StringModel(string value)
    {
        StringValue = value;
    }
}

ViewModel This class simply holds the Collection mentioned above as well as the property of the currently selected item. Additionally we have two functions corresponding to the buttons:

public void AddCopy()
{
    if (SelectedString == null)
        return;

    StringList.Add(new StringModel(SelectedString.StringValue));
}

public void AddClone()
{
    if (SelectedString == null)
        return;
    StringList.Add(SelectedString);
}

As you can see, since your StringModel is now a separate class, you can pass it by reference, or in case of copying, simply create a new one with the string content.

Obviously there are some additional checks to be make (hint: null pointer exception with the ObservableCollection, INotifyPropertyChanged implementation of ViewModel Properties), but this should get you started. Ask away if you have any questions.

  • Related