这是模型
class DataModel
{
string _inputvalue;
public string FirstName
{
get { return _inputvalue; }
set { _inputvalue= value; }
}
}
这是ViewModel
class MyViewModel : INotifyPropertyChanged
{
DataModel _data;
public MyViewModel ()
{
_data = new DataModel { FirstName= "DefaultName" };
}
public DataModel Data
{
get{return _data;}
set{_data = value;}
}
public string FirstName
{
get { return _data.FirstName; }
set {_data.FirstName= "NewName";
OnPropertyChanged("FirstName"):
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
这是查看
<TextBox Text="{Binding FirstName}"
Margin="8,59,76,122" />
我的问题是:
1)因为我刚刚启动MVVM,我想知道这是否正确的做法?
2)我希望我的FirstName
来自数据集。示例代码就像
string _getname=MyDS.Tables[0].Rows[0][1].ToString();
我可以在哪里放置此代码?
谢谢大家
答案 0 :(得分:3)
以下是视图模型的粗略示例:
class MyViewModel : INotifyPropertyChanged
{
private IModelRepository _repository;
public MyViewModel(IModelRepository repository)
{
_repository = repository;
Models = repository.GetAllModels();
}
public IEnumerable<DataModel> Models { get; set; }
}
public interface IModelRepository
{
IEnumerable<DataModel> GetAllModels();
}
public class MyRepository : IModelRepository
{
public IEnumerable<DataModel> GetAllModels()
{
// obviously nowhere near final code!!!
return new List<DataModel> {
new DataModel {
FirstName = MyDS.Tables[0].Rows[0][1].ToString()
}
};
}
}