[英]How to reuse the same code in several Display Templates?
I have 2 Display Templates that have the same code on a few lines. 我有2个显示模板,几行代码相同。
Is there is a way to move a common code to another file and reference that file in both templates? 有没有一种方法可以将通用代码移动到另一个文件并在两个模板中都引用该文件?
For example: 例如:
Display Template #1 and # 2 have the following common code: 显示模板#1和#2具有以下通用代码:
IFormatProvider formatProvider = System.Globalization.CultureInfo.CurrentCulture;
string formattedCurrency = null;
if (formatProvider.ToString().Equals("en-US"))
{
formattedCurrency = (@Model < 0 ? @Model.ToString("C", formatProvider) : (@Model).ToString("C", formatProvider));
}
else
{
formattedCurrency = (@Model < 0 ? "- " + @Math.Abs(@Model).ToString("C", formatProvider) : (@Model).ToString("C", formatProvider));
}
How can I move it to a separate file and reference that from both templates? 如何将其移至单独的文件并从两个模板引用该文件?
So my first option was to have the formattedCurrency
prop as a common function: 所以我的第一个选择是将
formattedCurrency
属性作为一个通用函数:
public class LocalizedViewModel {
private IFormatProvider formatProvider;
public float Currency { get; set; }
public string FormattedCurrency () {
if (formatProvider.ToString().Equals("en-US"))
{
return (this.Currency < 0 ? this.Currency.ToString("C", formatProvider) : (this.Currency).ToString("C", formatProvider));
}
else
{
return (this.Currency < 0 ? "- " + Math.Abs(this.Currency).ToString("C", formatProvider) : (this.Currency).ToString("C", formatProvider));
}
}
public LocalizedViewModel () {
formatProvider = System.Globalization.CultureInfo.CurrentCulture;
}
}
And then inherit both ViewModels from this base model 然后从该基本模型继承两个ViewModels
public class MyModel1: LocalizedViewModel {
public MyModel1() : base() {
}
}
public class MyModel2: LocalizedViewModel {
public MyModel2() : base() {
}
}
Then every time you create an object you have access to this prop: 然后,每次创建对象时,您都可以访问此道具:
var myModel = new Model1();
var myModel2 = new Model2();
myModel.Currency = 100;
myModel2.Currency = 200;
Now both viewmodels will have the formattedCurrency to display on any view, without the need on any extra view logic. 现在,两个视图模型都将具有formattedCurrency来显示在任何视图上,而无需任何额外的视图逻辑。 Hope this helps and could be a viable option to you.
希望这会有所帮助,并且对您来说是一个可行的选择。
myModel.FormattedCurrency();
myModel2.FormattedCurrency();
And render that property on any template. 并在任何模板上渲染该属性。 Again this is an alternative solution to achieve the same results.
同样,这是获得相同结果的替代解决方案。 But with a different approach.
但是采用了不同的方法。
Regards 问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.