我正在使用MVVM Light框架进行项目。
我有MainViewModel,它可以帮助我在视图模型之间导航。我有GoBack和GoTo方法。他们正在改变CurrentViewModel。
private RelayCommand<string> _goTo;
public RelayCommand<string> GoTo
{
get
{
return _goTo
?? (_goTo = new RelayCommand<string>(view
=>
{
SwitchView(view);
}));
}
}
private void SwitchView(string name)
{
switch (name)
{
case "login":
User = null;
CurrentViewModel = new LoginViewModel();
break;
case "menu":
CurrentViewModel = new MenuViewModel();
break;
case "order":
CurrentViewModel = new OrderViewModel();
break;
}
在MainWindow中,有内容控件和数据模板。
[...]
<DataTemplate DataType="{x:Type vm:LoginViewModel}">
<view:Login/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:MenuViewModel}">
<view:Menu/>
</DataTemplate>
[...]
<ContentControl VerticalAlignment="Top" HorizontalAlignment="Stretch"
Content="{Binding CurrentViewModel}" IsTabStop="false"/>
在我的OrderView(它是UserControl)中,我有一个文本块,其中应显示订单的TotalPrice。
<TextBlock Text="{Binding AddOrderView.TotalPrice}" Padding="0 2 0 0" FontSize="20" FontWeight="Bold" HorizontalAlignment="Right"/>
OrderViewModel具有属性TotalPrice,并且效果很好。当我调试时,我看到它已经更改,但是在我的视图中什么也没发生。
private decimal _totalPrice;
public decimal TotalPrice
{
get
{
_totalPrice = 0;
foreach (var item in Products)
{
item.total_price = item.amount * item.price;
_totalPrice += item.price * item.amount;
}
return _totalPrice;
}
set
{
if (_totalPrice == value)
return;
_totalPrice = value;
RaisePropertyChanged("TotalPrice");
}
}
OrderViewModel继承自BaseViewModel,它实现了INotifyPropertyChanged。
为什么我的文本块不更新/刷新?该怎么做?
当我使用后退按钮更改视图并再次转到OrderView时,我看到了更改!
我花了几天时间寻找解决方案,但没有任何帮助。
https://i.stack.imgur.com/K8lip.gif
因此,看起来好像在设置View时,没有重新加载就无法更改它。我不知道它是如何工作的。
答案 0 :(得分:0)
您不应在属性的getter或setter方法中进行计算或进行任何耗时的操作。这会大大降低性能。如果计算或操作很耗时,则应在后台线程中执行它,并在PropertyChanged
完成后引发Task
事件。这样,调用属性的getter或setter不会冻结UI。
您观察到的行为的解释:
单独使用属性 getter 而不是setter更改属性值的副作用是,新值不会传播到绑定目标。仅在发生PropertyChanged
事件时,绑定才会调用getter。因此,在getter中进行计算不会触发绑定刷新。现在,当重新加载页面时,所有绑定都将初始化绑定目标,并因此调用属性getter。
您必须设置TotalPrice
属性(而不是后备字段)才能触发绑定目标的刷新。但是,正如您已经经历过的那样,在系统中引发一个属性的PropertyChanged
事件
相同的吸气剂将导致无限循环,因此将导致StackOverflowException
。
同样,只要访问属性的getter,即使在TotalPrice
不变的情况下,也将始终执行计算。
TotalPrice
的值取决于Products
属性。为了最大程度地减少TotalPrice
计算的发生,请仅在Products
更改时进行计算:
OrderViewModel.cs
public class OrderViewModel : ViewModelBase
{
private decimal _totalPrice;
public decimal TotalPrice
{
get => this._totalPrice;
set
{
if (this._totalPrice == value)
return;
this._totalPrice = value;
RaisePropertyChanged();
}
}
private ObservableCollection<Product> _products;
public ObservableCollection<Product> Products
{
get => this._products;
set
{
if (this.Products == value)
return;
if (this.Products != null)
{
this.Products.CollectionChanged -= OnCollectionChanged;
UnsubscribeFromItemsPropertyChanged(this.Products);
}
this._products = value;
this.Products.CollectionChanged += OnCollectionChanged;
if (this.Products.Any())
{
SubscribeToItemsPropertyChanged(this.Products);
}
RaisePropertyChanged();
}
}
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (!e.Action.Equals(NotifyCollectionChangedAction.Move))
{
UnsubscribeFromItemsPropertyChanged(e.OldItems);
SubscribeToItemsPropertyChanged(e.NewItems);
}
CalculateTotalPrice();
}
private void ProductChanged(object sender, PropertyChangedEventArgs e) => CalculateTotalPrice();
private void SubscribeToItemsPropertyChanged(IList newItems) => newItems?.OfType<INotifyPropertyChanged>().ToList().ForEach((item => item.PropertyChanged += ProductChanged));
private void UnsubscribeFromItemsPropertyChanged(IEnumerable oldItems) => oldItems?.OfType<INotifyPropertyChanged>().ToList().ForEach((item => item.PropertyChanged -= ProductChanged));
private void CalculateTotalPrice() => this.TotalPrice = this.Products.Sum(item => item.total_price);
private void GetProducts()
{
using (var context = new mainEntities())
{
var result = context.product.Include(c => c.brand);
this.Products = new ObservableCollection<Product>(
result.Select(item => new Product(item.name, item.mass, item.ean, item.brand.name, item.price)));
}
}
public void ResetOrder()
{
this.Products
.ToList()
.ForEach(product => product.Reset());
this.TotalPrice = 0;
}
public OrderViewModel()
{
SetView("Dodaj zamówienie");
GetProducts();
}
}
还要确保Product
(Products
集合中的项目)也实现INotifyPropertyChanged
。这将确保在Products.CollectionChanged
属性更改时引发Product
事件。
要解决页面切换行为,您必须修改MainViewModel
类:
MainViewModel.cs
public class MainViewModel : ViewModelBase
{
// The page viewmodels
private Dictionary<string, ViewModelBase> PageViewModels { get; set; }
public Stack<string> ViewsQueue;
public MainViewModel()
{
User = new User(1, "login", "name", "surname", 1, 1, 1);
this.PageViewModels = new Dictionary<string, ViewModelBase>()
{
{"login", new LoginViewModel()},
{"menu", new MenuViewModel()},
{"order", new OrderViewModel()},
{"clients", new ClientsViewModel(User)}
};
this.CurrentViewModel = this.PageViewModels["login"];
this.ViewsQueue = new Stack<string>();
this.ViewsQueue.Push("login");
Messenger.Default.Register<NavigateTo>(
this,
(message) =>
{
try
{
ViewsQueue.Push(message.Name);
if (message.user != null) User = message.user;
SwitchView(message.Name);
}
catch (System.InvalidOperationException e)
{
}
});
Messenger.Default.Register<GoBack>(
this,
(message) =>
{
try
{
ViewsQueue.Pop();
SwitchView(ViewsQueue.Peek());
}
catch (System.InvalidOperationException e)
{
}
});
}
public RelayCommand<string> GoTo => new RelayCommand<string>(
viewName =>
{
ViewsQueue.Push(viewName);
SwitchView(viewName);
});
protected void SwitchView(string name)
{
if (this.PageViewModels.TryGetValue(name, out ViewModelBase nextPageViewModel))
{
if (nextPageViewModel is OrderViewModel orderViewModel)
orderViewModel.ResetOrder();
this.CurrentViewModel = nextPageViewModel;
}
}
}
您修改后的Product.cs
public class Product : ViewModelBase
{
public long id { get; set; }
public string name { get; set; }
public decimal mass { get; set; }
public long ean { get; set; }
public long brand_id { get; set; }
public string img_source { get; set; }
public string brand_name { get; set; }
private decimal _price;
public decimal price
{
get => this._price;
set
{
if (this._price == value)
return;
this._price = value;
OnPriceChanged();
RaisePropertyChanged();
}
}
private long _amount;
public long amount
{
get => this._amount;
set
{
if (this._amount == value)
return;
this._amount = value;
OnAmountChanged();
RaisePropertyChanged();
}
}
private decimal _total_price;
public decimal total_price
{
get => this._total_price;
set
{
if (this._total_price == value)
return;
this._total_price = value;
RaisePropertyChanged();
}
}
public Product(long id, string name, decimal mass, long ean, long brandId, decimal price, string imgSource)
{
this.id = id;
this.name = name;
this.mass = mass;
this.ean = ean;
this.brand_id = brandId;
this.price = price;
this.img_source = imgSource;
}
public Product(string name, decimal mass, long ean, string brandName, decimal price)
{
this.id = this.id;
this.name = name;
this.mass = mass;
this.ean = ean;
this.brand_name = brandName;
this.price = price;
}
public void Reset()
{
// Resetting the `amount` will trigger recalculation of `total_price`
this.amount = 0;
}
protected virtual void OnAmountChanged()
{
CalculateTotalPrice();
}
private void OnPriceChanged()
{
CalculateTotalPrice();
}
private void CalculateTotalPrice()
{
this.total_price = this.price * this.amount;
}
}
问题在于,切换到页面时,您始终创建了新的视图模型。当然,所有先前的页面信息都会丢失。您必须重用相同的视图模型实例。为此,只需将它们存储在专用的私有属性中,即可在构造函数中初始化一次。
答案 1 :(得分:-1)
它没有更新,因为您只在设置器中调用RaisePropertyChanged("TotalPrice");
。而在您的getter中是计算。因此,无论何时更改Products
属性或Products
集合的内容,都还需要调用RaisePropertyChanged("TotalPrice");
来通知视图TotalPrice
已被更新。
因此,如果您更改了item.amount或item.price中的任何一个,或者从Products列表中添加或删除了商品,则还需要致电。 RaisePropertyChanged("TotalPrice");
例如:
Products.Add(item);
RaisePropertyChanged("TotalPrice"); //This will tell you're View to check for the new value from TotalPrice