我有我的Model
類實現INotifyPropertyChanged
。 我的查看有5 TextBox
,2 Button
和ListView
來顯示網格。 在我的ViewModel
中,我之前在我的Model
類的ObservableCollection
中添加了默認值,並將其顯示爲ListView
。使用MVVM將數據保存到集合和顯示WPF
該按鈕的實現使用ICommand
和RelayCommand
完成。
現在我想從UI TextBox
的用戶添加數據到ObservableCollection
。我怎樣才能做到這一點? UI TextBox
具有Model
類的屬性。
我View
<ListView Name="UserGrid" Grid.Row="1" Margin="4,178,12,13" ItemsSource="{Binding UserDatas}" >
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,7,0,0" Name="txtUserId" VerticalAlignment="Top" Width="178" Text="{Binding UserId}" />
<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,35,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="178" Text="{Binding FirstName}" />
像這些有5個文本框
的Model
類:
public class User : INotifyPropertyChanged
{
private int userId;
private string firstName;
public int UserId
{
get
{
return userId;
}
set
{
userId = value;
RaisePropertyChanged("UserId");
}
}
}
視圖模型:
public class UsersViewModel:INotifyPropertyChanged
{
private ObservableCollection<User> userDatas;
public ObservableCollection<User> UserDatas
{
get
{
if (userDatas == null)
{
userDatas = new ObservableCollection<User>();
}
return userDatas;
}
set
{
userDatas = value;
RaisePropertyChanged("UserDatas");
}
}
}
private CommandBase _LoadCommand;
public ICommand LoadCommand
{
get
{
if (this._LoadCommand == null)
this._LoadCommand = new CommandBase(LoadData);
return this._LoadCommand;
}
}
private void LoadData(object obj)
{
//What need to be done here to access the textboxes of UI which are binded to User.cs class.
User newUser = new User();
UserDatas.Add(newUser);
}
現在我需要在LoadData方法寫入從UI採取inputfrom文本框,並將其存儲在我的ObservableCollection
使用Inotifypropertychanged。現在爲文本框創建一個getter setter字符串並綁定它。現在一旦你輸入了價值,就把它添加到你可觀察的集合中,它應該反映出來。 – Jerin
您不應該將模型綁定到UI,因爲UI應該與模型無關,只知道視圖模型 – Tseng
到目前爲止您有什麼?你能基本證明你是如何將你的屬性綁定到視圖/視圖模型上的嗎? – Tyress