【发布时间】:2014-06-20 08:11:35
【问题描述】:
我觉得这应该很简单,但我是 WPF 和 MVVM 的新手,只是不知道在哪里使用 MVVM。我搜索了 wpf+master+detail+mvvm,但我发现的所有示例都没有将数据保存回数据库/网络服务,这正是我想要完成的。
我应该在哪里使用 MVVM 中的 HttpClient 调用我的 Web API?当用户更改 TodoModel 的 Text 属性时,我想调用 Web API,例如PUT http://webapi.example.com/todos/5 请求正文如 { "Text":"This text is updated" }
型号:
public class TodoModel
{
public int Id { get; set; }
public string Title { get; set; }
public string Text { get; set; }
}
查看:
<Window x:Class="TodoMvvm.TodoView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TodoMvvm"
Title="TodoView" Height="350" Width="525">
<Window.DataContext>
<local:TodoViewModel />
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" x:Name="TodoListBox" ItemsSource="{Binding Todos}" DisplayMemberPath="Title" SelectedItem="{Binding Path=SelectedTodo}" />
<TextBox Grid.Column="1" x:Name="TodoTextBox" Text="{Binding Path=SelectedTodo.Text, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</Window>
视图模型:
public class TodoViewModel : INotifyPropertyChanged
{
public ObservableCollection<TodoModel> Todos { get; set; }
private TodoModel _selectedTodo;
public TodoModel SelectedTodo
{
get
{
// This triggers when changing the todo text, but it feels wrong to post changes back to the web api in a getter?!
return _selectedTodo;
}
set
{
_selectedTodo = value;
RaisePropertyChanged("SelectedTodo");
}
}
private ObservableCollection<TodoModel> GetTodoModels()
{
// Todo models should be retrieved from a web api.
var todos = new ObservableCollection<TodoModel>();
todos.Add(new TodoModel { Id = 1, Title = "Lorem", Text = "Lorem ipsum dolor sit amet" });
todos.Add(new TodoModel { Id = 2, Title = "Consectetur", Text = "Consectetur adipisicing elit" });
todos.Add(new TodoModel { Id = 3, Title = "Sed", Text = "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua" });
return todos;
}
public TodoViewModel()
{
Todos = GetTodoModels();
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
【问题讨论】:
标签: wpf mvvm asp.net-web-api