目前我的模型有10个属性,出于我们的目的,我将调用AnnualizedRate1
,AnnualizedRate2
,...,AnnualizedRate10
,这些属性通过十个显示在视图模型中的视图中属性Rate1
,Rate2
,...,Rate10
。我的一个观点在DataGrid
中显示了这些值。这非常重复,并且很难适应不断变化的要求。必须有比以下更好的方法。
模型(MyModel
):
public decimal AnnualizedRate1 { get { return this.AnnualizedRate(1); } }
public decimal AnnualizedRate2 { get { return this.AnnualizedRate(2); } }
...
public decimal AnnualizedRate10 { get { return this.AnnualizedRate(10); } }
其中MyModel.AnnualizedRate
是
public decimal AnnualizedRate(int i);
查看模型(MyViewModel
):
public decimal Rate1 { get { return myModel.AnnualizedRate1; } }
public decimal Rate2 { get { return myModel.AnnualizedRate2; } }
...
public decimal Rate10 { get { return myModel.AnnualizedRate10; } }
查看(MyView
):
xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit"
...
<dg:DataGrid>
<dg:DataGrid.Columns>
<dg:DataGridTextColumn
Header="Rate1"
Binding="{Binding Rate1, StringFormat=P}"
IsReadOnly="True"/>
<dg:DataGridTextColumn
Header="Rate2"
Binding="{Binding Rate2, StringFormat=P}"
IsReadOnly="True"/>
...
<dg:DataGridTextColumn
Header="Rate10"
Binding="{Binding Rate10, StringFormat=P}"
IsReadOnly="True"/>
</dg:DataGrid.Columns>
</dg:DataGrid>
有没有人有任何想法?
答案 0 :(得分:4)
这是RB Davidson所说的做的代码。如果您发现这符合您的要求,请给予他信任。他的回答是正确的。
在ViewModel中:
public class AnnualizedRateViewModel
{
public string Name { get; set; }
public decimal Rate { get; set; }
}
public MyViewModel : INotifyPropertyChanged
{
public MyViewModel()
{
AnnualizedRates = new ObservableCollection<AnnualizedRateViewModel>();
//I'd recommend your model having a GetAllRates() function rather than this,
//but for demo purposes, this works
for(int i = 1; i <= 10; i++)
{
AnnualizedRates.Add(new AnnualizedRateViewModel()
{
Name = string.Format("Rate {0}", i),
Rate = MyModel.AnnualizedRate(i)
});
}
}
private ObservableCollection<int> _annualizedRates;
public ObservableCollection<int> AnnualizedRates
{
get { return _annualizedRates; }
set
{
_annualizedRates = value;
//Raise OnNotifyPropertyChanged event from your
//implementation of INotifyPropertyChanged in your viewmodel
//the full implementation of this is outside the scope of this demo
}
}
}
从那里你实际上使用数据绑定来创建视图中的列。你绑定到这个AnnualizedRates集合。由于WPF工具包不能轻松实现,因此您必须编写一个值转换器,将ObservableCollection<AnnualizedRateViewModel>
转换为ObservableCollection<DataGridColumn>
。
<dg:DataGrid AutoGenerateColumns="false" Columns="{Binding AnnualizedRates, ValueConverter={StaticResource AnnualizedRatesToDataGridColumnCollectionConverter}}">
</dg:DataGrid>
你应该在这里学到的东西就是当你在想自己“重复”时,试着改为思考“收集”。
祝你好运......再次,信用RB Davidson。
答案 1 :(得分:1)
我会使用和ObservableCollection来存储数据并将网格绑定到。