I have a PersonModel object which is populated with a single record of person by using a method call. This object has got 2 properties viz first name and last name. In the view I have two textboxes that is bound to FirstName and LastName properties. The binding is done in the format Person.FirstName and it bounds properly. I have a Text Block that is bound to FullName property ({Binding Path = FullName, Mode=OneWay}). But this is not displaying anything. Below is the extract of my view model code.
public PersonModel Person
{
get { return _person; }
set
{
_person = value;
NotifyOfPropertyChange(() => Person);
}
}
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
NotifyOfPropertyChange(() => FirstName);
NotifyOfPropertyChange(() => FullName);
}
}
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
NotifyOfPropertyChange(() => LastName);
NotifyOfPropertyChange(() => FullName);
}
}
public string FullName
{
get { return $"{ FirstName } { LastName }"; }
}
Related
In xaml, I set my title to a value but it doesn't show in the window when I launch my app.
Similar to this post:
https://stackoverflow.com/questions/14397728/wpf-mvvm-bind-window-title-to-property#:~:text=The%20title%20is%20bound%20to%20window-viewmodel%20and%20the,because%20it%20inherits%20the%20DataContext%20of%20the%20window.
But I removed the datacontext and it didn't change anything. It showing "MyTitle" like in the preview is the desired behavior.
<Window x:Class="RED.Views.ShellView"
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:model="clr-namespace:RED.ViewModels"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
mc:Ignorable="d"
Height="700" Width="900" MinWidth="1100" MinHeight="700" Background="Gray" WindowStartupLocation="CenterScreen"
Title="MyTitle">
<!--d:DataContext="{x:Type model:ShellViewModel}"-->
<!--more markup-->
</Window>
This shows in the editor:
But launching the application shows the namespace name followed by some other stuff:
I am using Caliburn.micro, which I suspect is part of my issue but I cannot figure out how to get the title to update. This is my only window control in the whole project. My other xaml files are UserControls.
The ShellViewModel.cs file is 90% unused code that is a carry over from a tutorial I did. Here is that code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Caliburn.Micro;
using RED.Models;
using RED.Views;
namespace RED.ViewModels
{
public class ShellViewModel : Conductor<object>
{
//private string _lblLogged;
//private string lblLoggedInAs;
private string _firstName = "Tim"; // Don't change this
private string _lastName;
private BindableCollection<PersonModel> _people = new BindableCollection<PersonModel>();
private PersonModel _selectedPerson;
public ShellViewModel() //Constructor
{
People.Add(new PersonModel { FirstName = "Tim", LastName = "Corey" });
People.Add(new PersonModel { FirstName = "Bill", LastName = "Jones" });
People.Add(new PersonModel { FirstName = "Sam", LastName = "Yet" });
}
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
NotifyOfPropertyChange(() => FirstName);
NotifyOfPropertyChange(() => FullName); //Whenever a value of first name is changed, update fullname
}
}
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
NotifyOfPropertyChange(() => LastName);
NotifyOfPropertyChange(() => FullName); //Whenever a value of last name is changed, update fullname
}
}
public String FullName
{
get { return $"{ FirstName } { LastName }"; }
}
public BindableCollection<PersonModel> People
{
get { return _people; }
set { _people = value; }
}
public PersonModel SelectedPerson
{
get { return _selectedPerson; }
set
{
_selectedPerson = value;
NotifyOfPropertyChange(() => SelectedPerson);
}
}
//Return true or true for yes we can clear the text
public bool CanClearText(string firstName, string lastName)
{
//return !String.IsNullOrWhiteSpace(firstName) || !String.IsNullOrWhiteSpace(lastName);
if (String.IsNullOrWhiteSpace(firstName) && String.IsNullOrWhiteSpace(lastName))
{
return false;
}
else
{
return true;
}
}
//Perameters should start with lowercase, properties should start with uppercase
public void ClearText(string firstName, string lastName)
{
FirstName = "";
LastName = "";
}
public void btn_Phonebook()
{
if (Globals.isLoggedIn == true)
{
ActivateItem(new PhonebookViewModel());
}
else
{
MessageBox.Show("Please sign in to use the phonebook.");
}
}
public void btn_eRCPS()
{
ActivateItem(new WelcomeViewModel());
}
}
}
Everything works as expected except for this window title. Please let me know if there are other code bits that would be helpful and I will add them. Thanks!
In Caliburn.Micro, you should set the DisplayName property of the Conductor to change the window title:
public ShellViewModel() //Constructor
{
DisplayName = "MyTitle";
People.Add(new PersonModel { FirstName = "Tim", LastName = "Corey" });
People.Add(new PersonModel { FirstName = "Bill", LastName = "Jones" });
People.Add(new PersonModel { FirstName = "Sam", LastName = "Yet" });
}
I personally feel caliburn micro uses some bad techniques. I far prefer the community mvvm toolkit.
The work round for this is to explicitly bind the window title.
Title="{Binding WindowTitle}"
And, of course, add a WindowTitle string property to your viewmodel which returns a more suitable title.
You could probably override tostring on your viewmodel.
I have a puzzled problem of databinding in WPF.
There is a listbox in XAML which it has linked with ItemSource,
but when it runs, it shows the lists of class names.
so I have applied to DisplayMemberPath, but it doesn't helpful.
and also I'm wondering how I can access inside class from generic class.
Thanks.
result
puzzled.Member
puzzled.Member
puzzled.Member
puzzled.Member
<DockPanel>
<ListBox Name="lbxMbrList" DockPanel.Dock="Left" Width="200" Padding="10"></ListBox>
<ContentControl />
</DockPanel>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
members.Add(new Member("superman", "123-1234567", "address1"));
members.Add(new Member("batman", "111-111111", "address2"));
members.Add(new Member("goodman", "222-222222", "address3"));
members.Add(new Member("badman", "333-333333", "address4"));
lbxMbrList.ItemsSource = members;
lbxMbrList.DisplayMemberPath = members.MemberDetails; //<<it won't helpful
//var i = members.member.Name; //<<how can I access inside class?
//if (i == "superman")
//{
// MessageBox.Show("superman");
//}
}
public class Member
{
private string _name;
private string _phone;
private string _address;
public string Name { get { return _name; } set { _name = value; } }
public string Phone { get { return _phone; } set { _phone = value; } }
public string Address { get { return _address; } set { _address = value; } }
public Member() { }
public Member(string name, string phone, string address)
{
_name = name; _phone = phone; _address = address;
}
public string lbxMember
{
get { return string.Format("{0} - {1}", Name, Phone, Address); }
}
}
class MemberList : IEnumerable<Member>
{
private ObservableCollection<Member> memberList = new ObservableCollection<Member>();
public Member this[int i]
{
get {return memberList[i];}
set {memberList[i] = value;}
}
public void Add(Member member)
{
memberList.Add(member);
}
public void Remove(Member member)
{
memberList.Remove(member);
}
public IEnumerator<Member> GetEnumerator()
{
return memberList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
public Member member { get; set; } //<< it think I has misunderstood it
public string MemberDetails
{
get
{ return string.Format("{0} - {1}", member.Name, member.Phone, member.Address); }
}
}
You are assigning the output of your MemberDetails property to the DisplayMemberPath. Instead, you need to assign the name of the property as a string.
lbxMbrList.DisplayMemberPath = "MemberDetails";
For what its worth, this will be easier to work with if you use an ItemTemplate in the ListBox.
[Edit]
Also, as #Blam mentions in his answer, your MemberDetails property is defined in the wrong class, it needs be in the Member class.
lbxMbrList.DisplayMemberPath = "lbxMember";
or
lbxMbrList.DisplayMemberPath = "MemberDetails";
And MemberDetails need to be a property of Member (not MemberList)
I have a project in WPF with the MVVM-Pattern.
The view has a listview of Persons(FirstName, LastName, Town) and next to the list are the details of the person(FirstName,LastName,ZIP) with a button(Save).
If you click to a person on the left side, the person details on the right side will load automatically.
In the ViewModel I have an ObservableCollection of Person-Models. (Person list)
The Person Model includes some propertys like FirstName, LastName, Town, Zip. (Details).
When I change the ZIP, the Town will updated automatically(in the setter switch-case) e.g. ZIP '11111' Town 'Town1' / ZIP '22222' Town 'Town2'.
The Person Model includes also an ICommand "SavePerson" to Save Changes.
Now when i click to an item in the listview the details will load automatically.
When I change the FirstName or LastName and click "Save" the listview will change the First and the LastName of the selected item, that's ok.
Now when I change the ZIP from '12345' into '11111' the town in the listview is still the old one and not 'Town1'.
Have you an idea to fix this problem, without to implement the INotifyPropertyChanged-Interface in the Model?
Some code:
Model:
public class Person
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;
private string _zip = string.Empty;
private string _town = string.Empty;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName= value; }
}
public string ZIP
{
get { return _zip; }
set
{
switch (value)
{
case "11111":
this.Town = "Town1";
break;
case "22222":
this.Ort = "Town2";
break;
default:
break;
}
_zip = value;
}
}
public string Town
{
get { return _town; }
set { _town= value; }
}
public ICommand SaveNameCommand
{
get
{
return new DelegateCommand((param) => this.SaveName(param));
}
}
private void SaveName(object parameter)
{
string[] param = ((string)parameter).Split(new char[] { ':' });
FirstName = param[0];
LastName = param[1];
PLZ = param[2];
}
}
ViewModel:
public class PersonList
{
private readonly ObservableCollection<Person> _persons = new ObservableCollection<Person>();
private Person _currentSelectedPerson = new Person();
public PersonList()
{
this._persons.Add(new Person() { FirstName = "First1", LastName = "Last1", Ort = "Ort1", PLZ = "112" });
this._persons.Add(new Person() { FirstName = "First2", LastName = "Last2", Ort = "Ort2", PLZ = "122" });
this._persons.Add(new Person() { FirstName = "First3", LastName = "Last3", Ort = "Ort3", PLZ = "1132" });
}
public IEnumerable<Person> Persons
{
get { return this._persons; }
}
}
Since your Model should be loosely-coupled from your ViewModel, it makes sense that you might not want to implement INotifyPropertyChanged in your Model since it's most commonly associated with WPF; however, it's a C# interface and can be used in any type of application, so there's no harm implementing it. In fact, I'd suggest it's probably the best way. However, if you really don't want to implement it in your model classes, consider an event-subscriber model, where the Model raises an event when changed, and the ViewModel subscribes to it.
model.ValuesChanged += model_ValuesChanged;
private void model_ValuesChanged(object sender, EventArgs e)
{
RaisePropertyChanged("MyProperty");
}
I have absolutely no idea why you would want to not implement the INotifyPropertyChanged interface on your model class(es). Really, your only other option would be to implement it in your view model and expose all of your model properties there:
public string FirstName
{
get { return _currentSelectedPerson .FirstName; }
set { _currentSelectedPerson .FirstName = value; NotifyPropertyChanged("FirstName"); }
}
public string LastName
{
get { return _currentSelectedPerson .LastName; }
set { _currentSelectedPerson .LastName= value; NotifyPropertyChanged("LastName"); }
}
...
WPF and the INotifyPropertyChanged interface go hand in hand... at some stage, you're going to have to implement it.
The model Should implement INotifyPropertyChanged
chack INotifyPropertyChanged WPF
any other search of INotifyPropertyChanged will do as well
You need notification your View about changed in ViewModel.
For this use INotifyPropertyChanged. Any class that implements this interface,
notifies any listeners when a property has changed.
So you need to modify our Person class a little bit more:
public class Person : INotifyPropertyChanged
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;
private string _zip = string.Empty;
private string _town = string.Empty;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
RaisePropertyChanged("FirstName");
}
}
public string LastName
{
get { return _lastName; }
set
{
_lastName= value;
RaisePropertyChanged("LastName");
}
}
public string ZIP
{
get { return _zip; }
set
{
switch (value)
{
case "11111":
this.Town = "Town1";
break;
case "22222":
this.Town = "Town2";
break;
default:
break;
}
_zip = value;
RaisePropertyChanged("LastName");
RaisePropertyChanged("Town");
}
}
public string Town
{
get { return _town; }
set
{
_town= value;
RaisePropertyChanged("Town");
}
}
public ICommand SaveNameCommand
{
get
{
return new DelegateCommand((param) => this.SaveName(param));
}
}
private void SaveName(object parameter)
{
string[] param = ((string)parameter).Split(new char[] { ':' });
FirstName = param[0];
LastName = param[1];
PLZ = param[2];
}
}
I'm starting Caliburn Micro development and I have thought of an architecture where a viewmodel has properties, injected by MEF, which are other viewmodels. That way I can use contentcontrols in the view to position them the way I want.
public class ContactsProfileViewModel : Conductor<IContentItem>, IContactsModuleViewModel, IModule, IPartImportsSatisfiedNotification
{
private string name;
private string nameCaption;
private ISingleLineTextContentItem firstName;
private ISingleLineTextContentItem lastName;
public ContactsProfileViewModel()
{
this.DisplayName = "Contact Tab";
}
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
this.NotifyOfPropertyChange(() => Name);
}
}
public string NameCaption
{
get
{
return this.nameCaption;
}
set
{
this.nameCaption = value;
this.NotifyOfPropertyChange(() => NameCaption);
}
}
[Import(typeof(ISingleLineTextContentItem))]
public ISingleLineTextContentItem FirstName
{
get { return this.firstName; }
set
{
this.firstName = value;
this.NotifyOfPropertyChange(() => FirstName);
}
}
[Import(typeof(ISingleLineTextContentItem))]
public ISingleLineTextContentItem LastName
{
get { return this.lastName; }
set
{
this.lastName = value;
this.NotifyOfPropertyChange(() => LastName);
}
}
The viewmodel of SingleLineTextContentItem looks like this:
[Export(typeof(ISingleLineTextContentItem))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class SingleLineTextContentItemViewModel : PropertyChangedBase, ISingleLineTextContentItem
{
private string textBoxText;
private string caption;
public string TextBoxText
{
get { return textBoxText; }
set
{
textBoxText = value;
this.NotifyOfPropertyChange(() => TextBoxText);
}
}
public string Caption
{
get { return caption; }
set
{
this.caption = value;
this.NotifyOfPropertyChange(() => Caption);
}
}
}
Now, I need a way to bind the NameCaption property to the Caption property in a two-way manner. Is that possible? I'm I on the right track with this or is there a better way to do this?
Thanks,
Roland
What I do is instead of having a backing field just route to the other view model
public string NameCaption
{
get
{
return FirstName.Caption;
}
set
{
FirstName.Caption = value;
this.NotifyOfPropertyChange(() => NameCaption);
}
}
However if the Caption property on the ISingleLineTextContentItem can get set independently then you need to register changes on the event and have the view model listen to changes. So instead you need somthing along the lines of:
public string NameCaption
{
get
{
return FirstName == null ? string.Empty : FirstName.Caption;
}
set
{
if(FirstName != null)
FirstName.Caption = value;
}
}
[Import(typeof(ISingleLineTextContentItem))]
public ISingleLineTextContentItem FirstName
{
get { return this.firstName; }
set
{
if(this.FirstName != null)
this.FirstName.PropertyChanged -= FirstNameChanged;
this.firstName = value;
if(this.FirstName != null)
this.FirstName.PropertyChanged += FirstNameChanged;
this.NotifyOfPropertyChange(() => FirstName);
this.NotifyOfPropertyChange(() => NameCaption);
}
}
private void FirstNameChanged(object sender, PropertyChangedEventArgs e)
{
if(e.PropertName == "Caption")
this.NotifyOfPropertyChange(() => NameCaption);
}
Since either the Caption property or the FirstName property can change then we need to raise the event in the FirstName property and in the handler.
So I have the following model:
public class Person
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Address { get; set; }
public String EMail { get; set; }
public String Phone { get; set; }
}
public class Order
{
public Person Pers { get; set;}
public Product Prod { get; set; }
public List<Person> AllPersons { get; set; }
public Order(Person person, Product prod )
{
this.Pers = person;
this.Prod = prod;
AllPersons = database.Persons.GetAll();
}
}
And I have a WPF window used to edit an order.
I set the DataContext to Order.
public SetDisplay(Order ord)
{
DataContext = ord;
}
I have the following XAML:
<ComboBox Name="myComboBox"
SelectedItem = "{Binding Path=Pers, Mode=TwoWay}"
ItemsSource = "{Binding Path=AllPersons, Mode=OneWay}"
DisplayMemberPath = "FirstName"
IsEditable="False" />
<Label Name="lblPersonName" Content = "{Binding Path=Pers.FirstName}" />
<Label Name="lblPersonLastName" Content = "{Binding Path=Pers.LastName}" />
<Label Name="lblPersonEMail" Content = "{Binding Path=Pers.EMail}" />
<Label Name="lblPersonAddress" Content = "{Binding Path=Pers.Address}" />
However, the binding does not seem to work.......When I change the selected item , the labels do not update ....
Regards!!
Any reply is appreciated !!
Your model will need to fire change notifications. See INotifyPropertyChanged and INotifyCollectionChanged.
For INotifyPropertyChanged, you could use a base ViewModel class such as this one. For collections, ObservableCollection<T> does the hard work for you. However, in your case your collection won't change after the UI is bound to it, so you shouldn't need an observable collection. Regardless, I'd generally recommend using observable collections in your view model layer to save head-scratching should the code ever change.
An example of what this would look like is:
public class Person : ViewModel
{
private string firstName;
private string lastName;
private string email;
private string phone;
public string FirstName
{
get
{
return this.firstName;
}
set
{
if (this.firstName != value)
{
this.firstName = value;
OnPropertyChanged(() => this.FirstName);
}
}
}
public string LastName
{
get
{
return this.lastName;
}
set
{
if (this.lastName != value)
{
this.lastName = value;
OnPropertyChanged(() => this.LastName);
}
}
}
// and so on for other properties
}
public class Order : ViewModel
{
private readonly ICollection<Person> allPersons;
private Person pers;
private Product prod;
public Person Pers
{
get
{
return this.pers;
}
set
{
if (this.pers != value)
{
this.pers = value;
OnPropertyChanged(() => this.Pers);
}
}
}
public Product Prod
{
get
{
return this.prod;
}
set
{
if (this.prod != value)
{
this.prod = value;
OnPropertyChanged(() => this.Prod);
}
}
}
// no need for setter
public ICollection<Person> AllPersons
{
get
{
return this.allPersons;
}
}
public Order(Person person, Product prod )
{
this.Pers = person;
this.Prod = prod;
// no need for INotifyCollectionChanged because the collection won't change after the UI is bound to it
this.allPersons = database.Persons.GetAll();
}
}