我有一个应用程序,我试图保持数据访问和UI分开。为此,我有两个项目,一个用于UI,另一个用于数据访问。我遇到的问题是如何有效地将从UI项目中的配置文件获取的数据传递给数据访问项目中的类。
数据访问项目包含两个类......
Payment.cs
PaymentProcessor类负责制作Web API请求以获取" Payment"对象。我需要将一个字符串传递给Payment对象,以便它可以使用该字符串来查看付款中是否存在特定模式。
将此字符串传递给Payment类的最佳方法是什么?我是否在PaymentProcessor类上创建了一个属性,然后作为Payment类的属性传递?好像我正在玩#34;通过财产"。有更好的方法吗?
以下是一些示例代码,用于说明我如何使用这些类以及如何传递" ValidationString"。
// Code to execute in UI
var payProccessor = new PaymentProcessor();
payProccessor.ValidationStringToPass = "ABCDEFG";
payProccessor.ProcessPayment();
public class PaymentProcessor()
{
public string ValidationStringToPass {get; set;}
public void ProcessPayment()
{
// Get payment object collection
List<Payment> paymentCollection = GetPayments();
foreach(Payment p in paymentCollection)
{
p.ValidationString = this.ValidationStringToPass;
p.DoStuff();
}
}
}
public class Payment
{
string ValidationString {get; set;}
public void DoStuff()
{
// do stuff with the ValidationString
}
}
答案 0 :(得分:1)
以下是使用DependencyProperties和绑定的一种方法。
将您的付款类设为DependencyObject
public class Payment : DependencyObject
{
public static readonly DependencyProperty ValidationStringProperty =
DependencyProperty.Register("ValidationString", typeof(string), typeof(Payment), new PropertyMetadata(new PropertyChangedCallback(OnValidationStringChanged)));
public string ValidationString
{
get { return (string)this.GetValue(Payment.ValidationStringProperty); }
set
{
this.SetValue(Payment.ValidationStringProperty, value);
}
}
private static void OnValidationStringChanged(object sender, DependencyPropertyChangedEventArgs e)
{
// do stuff all that stuff you wanted to do ValidationString
}
}
然后让PaymentProcessor实现INotifyPropertyChanged
public class PaymentProcessor : INotifyPropertyChanged
{
public PaymentProcessor()
{
}
private string _validationStringToPass;
public string ValidationStringToPass
{
get { return _validationStringToPass; }
set
{
_validationStringToPass = value;
OnPropertyChanged("ValidationStringToPass");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
//Get your payments here, might want to put this in the constructor
public void GetPayments()
{
Binding bind = new Binding() { Source = this, Path = new PropertyPath("ValidationStringToPass") };
Payment pay = new Payment();
BindingOperations.SetBinding(pay, Payment.ValidationStringProperty, bind);
Payment pay1 = new Payment();
BindingOperations.SetBinding(pay1, Payment.ValidationStringProperty, bind);
}
}
然后在您的UI代码中,您可以执行以下操作
var payProccessor = new PaymentProcessor();
payProccessor.GetPayments();
payProccessor.ValidationStringToPass = "ABCDEFG";
当您在PaymentProcessor中更改ValidationStringToPass属性时,它将更新您在GetPayments方法中绑定的Payments中的ValidationString属性。