Why can databinding be seen working in the designer:
Click to show image: Databinding seems OK
But runtime shows nothing?
Click to show image: No Data, no usercontrol?
Outline code structure:
ViewModelBase : baseclass inheriting from INotofyPropertychanged
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = "")
{
if (EqualityComparer<T>.Default.Equals(storage, value))
return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
}
SiteViewModel : Model class with Id/Name/Description Properties
public class SiteViewModel : ViewModelBase
{
private int _SiteID;
private string _Name;
private string _Description;
public int SiteID
{
get { return _SiteID; }
set { SetProperty(ref _SiteID, value); }
}
public string Name
{
get { return _Name; }
set { SetProperty(ref _Name, value); }
}
public string Description
{
get { return _Description; }
set { SetProperty(ref _Description, value); }
}
}
SitesViewModel: ObservableCollection of SiteViewModel
public class SitesViewModel : ViewModelBase
{
private ObservableCollection<SiteViewModel> _AllSites;
public ObservableCollection<SiteViewModel> AllSites {
get { return _AllSites; }
set { SetProperty<ObservableCollection<SiteViewModel>>(ref _AllSites, value); }
}
public SitesViewModel()
{
AllSites = new ObservableCollection<SiteViewModel>();
for (int count = 1; count <= 3; count++)
{
AllSites.Add(new SiteViewModel { SiteID = count, Name = "Test" + count.ToString(), Description = "Site:" + count.ToString() } );
}
}
}
SiteManagerControl : UserControl with a SitesViewModel property _AllSites
public partial class SiteManagerControl : UserControl
{
private SitesViewModel _AllSites;
public SitesViewModel AllSites
{
get { return _AllSites; } //<-- Breakpoint not hit!
set {
if (_AllSites != value)
{ _AllSites = value;
OnPropertyChanged("AllSites");
}}
}
public SiteManagerControl(){
_AllSites = new SitesViewModel();}
(XAML can be seen in the first linked image above, Note the breakpoint not hit line in the above). The user control is hosted in a Tabcontrol that is part of an ObservableCollection. I don't think this is an issue in the databinding. Will post the code for the tabs if needed.
There are no errors in the Debug Output window to indicate why the databinding is failing.
Your listview DataContext Data binding is with object from class(SitesViewModel)
This class has property named (AllSites) that has oveservable collection property named (AllSites) as well.
so I think you have to fix the ItemSource binding in the list view like this:
ItemsSource="{Binding AllSites.AllSites}"
Will's comment (thanks!) above pointed me in the right direction: Changed MainWindow.xaml to contain:
<DataTemplate DataType="{x:Type vm:SitesViewModel}">
<uc:SitesView></uc:SitesView>
</DataTemplate>
Also followed this : http://codingtales.blogspot.co.uk/2010/02/creating-complete-tabbed-interface-in.html to rework my tab interface
Related
This is the XAML of the radio. Nothing else is editing this. Once this is set it is not changing. But somehow no matter what it is setting the XML to "false".
Here is how I save the XML file (works just fine).
There are 3 radio buttons, as you can see, that I am trying to get set to false or true but they all just get saved as false.
<RadioButton x:Name="sx80" Content="Cisco SX80" HorizontalAlignment="Left" Margin="701,244,0,0" VerticalAlignment="Top" GroupName="codecType" TabIndex="17" FontWeight="Normal" Height="25" Width="95" Padding="0,2"/>
class SaveXml
{
public static void savedata(object obj, string filename)
{
XmlSerializer sr = new XmlSerializer(obj.GetType());
TextWriter writer = new StreamWriter(filename);
sr.Serialize(writer, obj);
writer.Close();
}
}
Here is the main class that tells it what information we are saving to the XML file.
public class information
{
private string city;
private string chairCount;
private string stateSelect;
private string HostNameIPTyped;
private string VTCmac;
private string vtcUser;
private string vtcPass;
private string VTCserial;
private string AssetTag;
private string SIPURI;
private string SystemName;
private string firstName;
private string lastName;
private string contactPhone;
private string provisionerName;
private string provisionerInitials;
private string provisionDate;
private bool sx80;
private bool codecPlus;
private bool codecPro;
public string postcity
{
get { return city; }
set { city = value; }
}
public string postchairCount
{
get { return chairCount; }
set { chairCount = value; }
}
public string poststateSelect
{
get { return stateSelect; }
set { stateSelect = value; }
}
public string postHostNameIPTyped
{
get { return HostNameIPTyped; }
set { HostNameIPTyped = value; }
}
public string postVTCmac
{
get { return VTCmac; }
set { VTCmac = value; }
}
public string postvtcUser
{
get { return vtcUser; }
set { vtcUser = value; }
}
public string postvtcPass
{
get { return vtcPass; }
set { vtcPass = value; }
}
{ e164 = value; }
}
public string postVTCserial
{
get { return VTCserial; }
set { VTCserial = value; }
}
public string postAssetTag
{
get { return AssetTag; }
set { AssetTag = value; }
}
public string postSIPURI
{
get { return SIPURI; }
set { SIPURI = value; }
}
public string postSystemName
{
get { return SystemName; }
set { SystemName = value; }
}
public string postfirstName
{
get { return firstName; }
set { firstName = value; }
}
public string postlastName
{
get { return lastName; }
set { lastName = value; }
}
public string postcontactPhone
{
get { return contactPhone; }
set { contactPhone = value; }
}
public string postprovisionerName
{
get { return provisionerName; }
set { provisionerName = value; }
}
public string postprovisionerInitials
{
get { return provisionerInitials; }
set { provisionerInitials = value; }
}
public string postprovisionDate
{
get { return provisionDate; }
set { provisionDate = value; }
}
public bool postsx80
{
get { return sx80; }
set { sx80 = value; }
}
public bool postcodecPlus
{
get { return codecPlus; }
set { codecPlus = value; }
}
public bool postcodecPro
{
get { return codecPro; }
set { codecPro = value; }
}
}
The code you posted doesn't show any data binding on the RadioButton or how you've set your DataContext. But you said in the comments that the strings are working so I assume you've set the DataContext somewhere. If you can update your question to show how your Window/View is bound to the information object it will be easier to give you a more accurate solution. You also said the following in one of your comments:
Yes, it is actually being saved as false. If it didn't find a value it would just show nothing. :-) <postsx80>false</postsx80>
The default value for a bool is actually false, so even if no value is retrieved from your RadioButton, your XML file will still show false.
Your RadioButton's would normally be bound like this, depending on how your DataContext is set. Notice the Binding in the IsChecked property. The Mode=TwoWay means that the UI can set the value of the property and not just read it:
<RadioButton x:Name="sx80" Content="Cisco SX80" IsChecked="{Binding Info.postsx80, Mode=TwoWay}" />
In the code behind of this Window I have created a public property called Info which contains an instance of your information class. The RadioButton above is bound the the postsx80 property of this information instance so you would need to pass this instance to your savedata method like below.
public partial class MainWindow : Window
{
public information Info { get; set; } = new information(); // The UI is bound to this instance
public MainWindow()
{
InitializeComponent();
this.DataContext = this; // I've set the Window's DataContext to itself
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SaveXml.savedata(Info, "somefile.xml");
}
}
You should also implement INotifyPropertyChanged which will notify the UI when a property's value has changed. For example your information class could look like this:
// You will need to add the following namespaces
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace YourAppsNamespace
{
public class information : INotifyPropertyChanged // Implement the INotifyPropertyChanged interface
{
private bool sx80;
public bool postsx80
{
get { return sx80; }
set {
sx80 = value;
OnPropertyChanged(); // Notify the UI that this property's value has changed
}
}
// This code raises the event to notify the UI which property has changed
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
You would need to add OnPropertyChanged() to the setters of all of your properties.
You also mentioned in the comments that you don't know how to use auto properties. An auto property is basically a shorter way to write a property when there are no additional actions which need to be performed when getting or setting a value. For example, this:
private bool someBool;
public bool SomeBool
{
get { return someBool; }
set { someBool = value; }
}
Would just become:
public bool SomeBool { get; set; }
There is no need to create the private variable or define the body of the getter and setter. This is handled automatically for you. This is only suitable if you don't need to perform any additional actions in the getter or setter. So in my example above where we need to call OnPropertyNotifyChanged() in the setter, you wouldn't be able to use an auto property.
An additional tip is that you can simply type prop in Visual Studio and press Tab twice to insert an auto property without having to type it out yourself. You then simply change the data type, press Tab again to move to the name and change that. The same can be done for a full property like the ones you wrote by typing propfull.
I implemented INotifyPropertyChanged as recommended by many threads.
Implementation 1
public class Notifier : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string pName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(pName));
}
}
public class Model : Notifier, IDataErrorInfo
{
private string name;
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged("name_changed"); }
}
}
And the viewmodel consists of the model and command to make changes to model properties.
public class ViewModel : Notifier
{
private Model _model;
public Model Model
{
get { return _model; }
set { _model = value; OnPropertyChanged("model_changed"); }
}
private ICommand _cmd;
public ICommand Command
{
get { return _cmd; }
set { _cmd = value; }
}
public void ExecuteCommand(object para)
{
Console.WriteLine("Command executed");
Model.Name = "new name";
}
}
VM is then binded to the view.
<TextBox HorizontalAlignment="Center" VerticalAlignment="Center" Width="100">
<TextBox.Text>
<Binding Path="Model.Name" Mode="TwoWay" NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True">
<Binding.ValidationRules>
<ExceptionValidationRule></ExceptionValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
When the command is executed, the TextBox does not get updated to new value.
However, if I implement the INotifyPropertyChanged like this instruction, the binding works.
Implementation 2
public class Notifier : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T field, T newValue, [CallerMemberName]string propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(field, newValue))
{
field = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
return true;
}
return false;
}
}
public class Model : Notifier, IDataErrorInfo
{
private string name;
public string Name
{
get { return name; }
set { SetProperty(ref name, value); }
}
}
What is missed in the first method?
The main problem with Implementation 1 is that the string parameter of your OnPropertyChanged method needs to be the exact property name that is being changed. For your two examples, "model_changed" should be changed to "Model"
and "name_changed" should read "Name". Here are two great techniques to mitigate potential human error with the typing of literal string names:
1. Use the CallerMemberName Attribute
If you are allowed and have access to the System.Runtime.CompilerServices namespace, you can write your base class as such to have the property name automatically passed as the string parameter of the OnPropertyChanged method:
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class Notifier : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string pName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(pName));
}
}
Then you can simply call OnPropertyChanged() in your property's getter.
2. Use the nameof keyword
Alternatively, you may simply replace the literal typed property name with nameof(<InsertPropertyNameHere>) which will return the name without any risk of mistyping, like this example:
public class Model : Notifier, IDataErrorInfo
{
private string name;
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged(nameof(Name)); }
}
}
Please add property name like this.
public class Model : Notifier, IDataErrorInfo
{
private string name;
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged("Name"); }
}
}
I've a problem with DataGrid in Prism MVVM.
When I edited entity in other window, then I create new window with DataGrid is not updated. Only run application again help. It's my code:
<DataGrid Name="ClientsTable" IsReadOnly="True" ItemsSource="{Binding Path=ListOfClients, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" AutoGeneratingColumn="DataGrid_AutoGeneratingColumn" Margin="22,10,22,55" Width="800"/>
Part of ViewModel for this window:
public ListOfClientsViewModel(IClientService clientService, IEventAggregator eventAggregator)
{
this.clientService = clientService;
this.eventAggregator = eventAggregator;
ListOfClients.AddRange(clientService.GetAllClientsForList());
}
private ObservableCollection<ClientForList> listOfClients = new ObservableCollection<ClientForList>();
public ObservableCollection<ClientForList> ListOfClients
{
get { return listOfClients; }
set { SetProperty(ref listOfClients, value); }
}
And part of model from collection. It's in other project.
public class ClientForList : INotifyPropertyChanged
{
private string id;
private string name;
private string firstname;
private string lastname;
private string city;
private DateTime createdDate;
[DisplayName("Numer klienta")]
public string Id
{
get { return id; }
set
{
if (value != id)
{
id = value;
OnPropertyChanged();
}
}
}
[DisplayName("Nazwa")]
public string Name
{
get { return name; }
set
{
if (value != name)
{
name = value;
OnPropertyChanged();
}
}
}
[DisplayName("ImiÄ™")]
public string Firstname
{
get { return firstname; }
set
{
if (value != firstname)
{
firstname = value;
OnPropertyChanged();
}
}
}
[.....]
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
And, when I edit entity in other window, then I open window with DataGrid by:
void ExecuteListOfClients()
{
ListOfClients listOfClientsWindow = new ListOfClients();
listOfClientsWindow.DataContext = new ListOfClientsViewModel(IClientService, EventAggregator);
listOfClientsWindow.ShowDialog();
}
And data in DataGrid is old. When I restart application data is actual. Help!
Instead of
set { SetProperty(ref listOfClients, value); }
do
set { SetProperty(listOfClients, value); }
and instead of
ListOfClients.AddRange(clientService.GetAllClientsForList());
do
ListOfClients = clientService.GetAllClientsForList().ToObservableCollection();
You may need to implement the extension ToObservableCollection().
Another solution is to change the property ListOfClients as a normal IList and then implment INotifyPropertyChanged inside your view model
Ok, I solved part of the problem.
I have cut the window creation without the manual creation of the ViewModel on:
void ExecuteListOfClients()
{
ListOfClients listOfClientsWindow = new ListOfClients();
listOfClientsWindow.ShowDialog();
}
And in xaml ListOfClients.xaml I changed to:
prism:ViewModelLocator.AutoWireViewModel="True"
And now, after reopening the window, it shows refreshed data;)
But there is still a problem. I've done the LoadData method, which is done in the constructor and assigns data to the ObservableCollection. It works. I have set a button for it and after editing the client I click to load new data and unfortunately nothing happens. In the future I want this method to be called from the EventAggregator after editing the client, but for now I have made a button to test and unfortunately it does not work.
It works. The problem was not in the WPF itself, nor was the view strangely enough. The problem lay in EntityFramework. I had to modify the command choosing data from the database to the collection:
var clients = db.Clients.AsNoTracking().ToList();
something i do wrong? anyone gives some suggestions
according to msdn
Indexers of a property can be specified within square brackets following the property name where the indexer is applied. For instance, the clause Path=ShoppingCart[0] sets the binding to the index that corresponds to how your property's internal indexing handles the literal string "0". Multiple indexers are also supported.
i put Indexers of a property in my xaml
<Image Source="{Binding ImagePathList[0]}" Height="50" Width="50" Grid.Row="0" Grid.Column="0" VerticalAlignment="Top" Margin="0,7,7,0" Grid.RowSpan="2">
i do not give the viewmodel code because i am pretty sure ListImagePathList have data.
EDIT*
more detail: ImagePathList[0] is a web image url
EDIT FOR Brendan
model is Article
public class Article : INotifyPropertyChanged
{
private long _Id;
public long ID
{
get { return _Id; }
set
{
if (_Id != value)
{
_Id = value;
NotifyPropertyChanged();
}
}
}
private string _subject;
public string Subject
{
get
{
return _subject;
}
set
{
if (_subject != value)
{
_subject = value;
NotifyPropertyChanged();
}
}
}
private string _words;
public string Words
{
get
{
return _words;
}
set
{
if (_words != value)
{
_words = value;
NotifyPropertyChanged();
}
}
}
private DateTime _publishDate;
public DateTime PublishDate
{
get
{ return _publishDate; }
set
{
if (_publishDate != value)
{
_publishDate = value;
NotifyPropertyChanged();
}
}
}
public List<string> ImagePathList = new List<string>();
private string _firstImage;
public string FirstImage
{
get
{
return _firstImage;
}
set
{
if (_firstImage != value)
{
_firstImage = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
ArticleViewModel is in below; All data returned from network is correct!
public class ArticleListViewModel : INotifyPropertyChanged
{
public ArticleListViewModel()
{
this.ArticleCollection = new ObservableCollection<Article>();
}
public ObservableCollection<Article> ArticleCollection
{
get;
private set;
}
public void LoadPage(int pageNumber)
{
if (pageNumber == 1)
{
this.ArticleCollection.Clear();
}
IsLoading = true;
ReadArticleList(pageNumber);
}
private async void ReadArticleList(int pageNumber)
{
try
{
List<Article> articleList = new List<Article>();
articleList = await CollectionHttpClient.GetArticlesByPageAsync(pageNumber);
this.ArticleCollection.Add(item);
}
}
catch(Exception ex)
{
if (ex.HResult == -2146233088 && ex.Message.Equals("Response status code does not indicate success: 404 ()."))
{
MessageBox.Show("The network is not set right. Internet cannot be accessed.");
}
else
{
MessageBox.Show("sorry, no data.");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
The XAML code you show is fine.
There may be a problem with the DataContext. Maybe the page DataContext has not been set? Or maybe the the DataContext has changed e.g. inside an ItemTemplate
Otherise the problem is probably to do with the bound property. Try the following
private ObservableCollection<string> _imagePathList = new ObservableCollection<string>();
public ObservableCollection<string> ImagePathList {
get { return this._imagePathList; }
set {
if (this._imagePathList != value)
{
this._imagePathList = value;
// I'm going to assume you have the NotifyPropertyChanged
// method defined on the view-model
this.NotifyPropertyChanged();
}
}
}
ObservableCollection is in System.Collections.ObjectModel and is like List but if elements are added/removed then the PropertyChanged event is fired. Also note that any bound property must have a get associated with it for it to work at all.
Another possibility is that ImagePathList was not assigned to or is empty - in which case, make sure you assign to it!
In case you have not yet implemented the NotifyPropertyChanged method, here it is ...
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
You will also need to add INotifyPropertyChanged interface to the containing class e.g.
public class MyViewModelClass : INoftifyPropertyChanged
{
...
}
I think the problem concerns the place where your images come from. As it is said at MSDN:
You can set the Source by specifying an absolute URL (e.g. http://contoso.com/myPicture.jpg) or specify a URL relative to the XAP file of your application.
You can set this property in XAML, but in this case you are setting the property as a URI. The XAML behavior relies on underlying type conversion that processes the string as a URI, and calls the BitmapImage(Uri) constructor. This in turn potentially requests a stream from that URI and returns the image source object.
Just for test - place some images in your project and then set ImagePathList to them. See if that works (it should as I think). Or see if you can get BitmapImage(ImagePathList);
It's hard for me to say now (as I don't know how your ImagePathList looks like) what could be a reason of the failure. But if I were you, I would test this.
I would advise to use a property (or you can use converter which will also do the job):
// a property in your class
public Uri FirstImage
{
get
{
return new Uri(ImagePathList.FirstOrDefault(), UriKind.Absolute);
}
}
On the other hand if you are downloading images to IsolatedStorage then you will have to use another property, that will load BitmapImage from IS:
public BitmapImage FirstImage // getter - BitmapImage
{
get
{
if (String.IsNullOrEmpty(ImagePath[0])) return null;
BitmapImage temp = new BitmapImage();
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
using (IsolatedStorageFileStream file = ISF.OpenFile(ImagePath[0], FileMode.Open, FileAccess.Read))
temp.SetSource(file);
return temp;
}
}
Hope this helps.
I am having an issue getting my model changes updated back into my viewmodel so i can display. In this example i have a label and a button, when i press the button it will execute some business logic, and should update the label on screen. However, when my model changes the view will not. Any Idea on what i am doing wrong here?
View-
<Window.DataContext>
<vm:ViewModel>
</Window.DataContext>
<Grid>
<Label Content="{Binding Path=Name}"/>
<Button Command={Binding UpdateBtnPressed}/>
</Grid>
ViewModel
public ViewModel()
{
_Model = new Model();
}
public string Name
{
get{return _Model.Name;}
set
{
_Model.Name = value;
OnPropertyChanged("Name");
}
}
public ICommand UpdateBtnPressed
{
get{
_UpdateBtn = new RelayCommand(param => UpdateLabelValue());
return _UpdateBtn;
}
private void UpdateLabelValue()
{
_Model.Name = "Value Updated";
}
Model
private string name = "unmodified string";
public string Name
{
get{return name;}
set{name = value;}
}
Try this:
private void UpdateLabelValue()
{
Name = "Value Updated";
}
It seems you've missed to implement the INotifyPropertyChanged interface.
Your model must implement INotifyPropertyChanged such as;
public class Personel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _name;
public string Name
{
get { return _name; }
set { _name = value; OnChanged("Name");}
}
void OnChanged(string pn)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(pn));
}
}
}