我不完全确定为什么这不是更新。因此,在我的应用程序中,您可以使用文本框修改右侧的用户名。这些变化实时反映在左侧。当您点击'添加新许可证'按钮时,它会创建一个新许可证并将其添加到选定的客户。然而,列表视图列'Lincenes'似乎没有更新以反映客户拥有的许可数量。作为测试,我在我的Obs系列中放置了打印声明可观察的集合没有发射setter或更新C#wpf
private ObservableCollection<License> licenses;
public ObservableCollection<License> Licenses
{
get { return licenses ?? (licenses = new ObservableCollection<License>()); }
set
{
Console.Write("Modified");
Set(ref licenses, value);
RaisePropertyChanged(nameof(LicensesCount));
}
}
但是我注意到它从来没有打印出于某种原因。我非常难以做什么或改变。以下是我的代码的主要部分。无论是客户和许可类对象是基类的inotify的...
Customer.cs和License.cs类
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Input;
using WpfApplication1.Helper;
namespace WpfApplication1.Model
{
public class Customer : NotifyBase
{
private string firstName;
public string FirstName
{
get { return firstName; }
set { Set(ref firstName, value); }
}
public string LicensesCount
{
get { return this.Licenses.Count.ToString(); }
}
private ObservableCollection<License> licenses;
public ObservableCollection<License> Licenses
{
get { return licenses ?? (licenses = new ObservableCollection<License>()); }
set
{
Console.Write("Modified");
Set(ref licenses, value);
RaisePropertyChanged(nameof(LicensesCount));
}
}
public Customer(string firstname, string lastname, string email, string company)
{
this.FirstName = firstname;
}
// Commands
private ICommand addNewLicense_Command;
public ICommand AddNewLicense_Command
{
get { return addNewLicense_Command ?? (addNewLicense_Command = new RelayCommand<Customer>(n =>{ AddNewLicense_Execute(n); }));}
}
public void AddNewLicense_Execute(Customer customer)
{
Licenses.Add(new License("Paint"));
}
}
public class License : NotifyBase
{
private string product;
public string Product
{
get { return product; }
set { Set(ref product, value); }
}
public License(string product)
{
this.Product = product;
}
}
}
NotifyBase.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace WpfApplication1.Helper
{
public abstract class NotifyBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
protected bool Set<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
RaisePropertyChanged(propertyName);
return true;
}
}
}
下面是该解决方案的链接:Solution Files
我明白了,这清除了一切。感谢您的帮助。 有没有办法可以将它添加到ObservableObjectEx类?所以它适用于任何Observable对象的类。这样做似乎更安全。 – JokerMartini
对不起,我无法想象简单的方法来自动化这... –
谅解。尽管谢谢你的帮助!你的答案是正确的 – JokerMartini