gpt4 book ai didi

wpf - WPF MVVM 中的两个 'self-updating' 属性

转载 作者:行者123 更新时间:2023-12-01 01:38:18 25 4
gpt4 key购买 nike

考虑到您在 WPF 中有一个 MVVM 架构,例如 Josh Smith's examples

您将如何实现两个相互更新的“同步”属性?我的模型中有一个 Price 属性和一个 PriceVatInclusive 属性。

- 当价格发生变化时,我希望看到增值税包含的价格自动为“价格 * 1.21”。

-反之亦然,当 PriceVatInclusive 更改时,我希望价格为“PriceVatInclusive/1.21”

对此有何想法?

如果您的模型是 Entity Framework 条目怎么办?那么你不能使用上面的方法......不是吗?你应该把计算代码放在 ViewModel 中还是......?

最佳答案

单程:

    public class Sample : INotifyPropertyChanged
{
private const double Multiplier = 1.21;
#region Fields
private double price;
private double vat;
#endregion

#region Properties
public double Price
{
get { return price; }
set
{
if (price == value) return;
price = value;
OnPropertyChanged(new PropertyChangedEventArgs("Price"));
Vat = Price * Multiplier;
}
}

public double Vat
{
get { return vat; }
set
{
if (vat == value) return;
vat = value;
OnPropertyChanged(new PropertyChangedEventArgs("Vat"));
Price = Vat / Multiplier;
}
}
#endregion

#region INotifyPropertyChanged Members
protected void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler ev = PropertyChanged;
if (ev != null)
{
ev(this, e);
}
}
public event PropertyChangedEventHandler PropertyChanged;

#endregion
}

如果可以从 DependencyObject 派生,则可以使用 Dependency Properties。
public class Sample : DependencyObject
{
private const double Multiplier = 1.21;

public static readonly DependencyProperty VatProperty =
DependencyProperty.Register("Vat", typeof(double), typeof(Sample),
new PropertyMetadata(VatPropertyChanged));

public static readonly DependencyProperty PriceProperty =
DependencyProperty.Register("Price", typeof(double), typeof(Sample),
new PropertyMetadata(PricePropertyChanged));

private static void VatPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Sample sample = obj as Sample;
sample.Price = sample.Vat / Multiplier;
}

private static void PricePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Sample sample = obj as Sample;
sample.Vat = sample.Price * Multiplier;
}

#region Properties
public double Price
{
get { return (double)GetValue(PriceProperty); }
set { SetValue(PriceProperty, value); }
}

public double Vat
{
get { return (double)GetValue(VatProperty); }
set { SetValue(VatProperty, value); }
}
#endregion
}

关于wpf - WPF MVVM 中的两个 'self-updating' 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/372660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com