我对 XAML 和 Windows 8 应用程序编程和整体编程相当陌生。这几天我一直在尝试。我有一个名为 PeopleConnector 的 ViewModel,它包含一个可观察的人集合我已经将我的 XAML 页面的 DataContext 设置为我的 ViewModel。现在我希望能够在我的视图中创建一个新的人,使用来自文本框的输入,并通过两种方式数据绑定将其显示在我的列表中。这样做的正确方法是什么。我可以在我的 XAML 页面后面的代码中完成这项工作,但是我正在跳过我的 viewModel。这可以通过我的 ViewModel 实现吗?
代码
Person 类是一个简单的 Poco 类,继承 BindableBase
我的 ViewModel(人员连接器)
class PeopleConnector : BindableBase
{
private ObservableCollection<Person> _people;
public ObservableCollection<Person> People
{
get { return _people; }
set { _people = value; OnPropertyChanged(); }
}
public PeopleConnector()
{
People = new ObservableCollection<Person>();
People.Add(new Person { Name = "Iris", About = "Developer that loves Metro style" });
People.Add(new Person { Name = "Paul", About = "DBA with a thing for SQL Server 2012" });
}
public Person NewPerson { get; set; }
public void AddNewPerson()
{
People.Add(new Person { Name = NewPerson.Name, About = NewPerson.About });
}
}
我的视图(XAML 页面)
<Page.DataContext>
<local:PeopleConnector/>
</Page.DataContext>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" >
<StackPanel Orientation="Horizontal" >
<ListView x:Name="AllItemsView"
Width="200"
Margin="40,20,0,0"
Height="400"
VerticalAlignment="Top"
Background="DarkGray"
ItemsSource="{Binding People}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"></TextBlock>
<TextBlock TextWrapping="Wrap" Text="{Binding Path=About}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackPanel Width="200" Margin="20,50,0,0" Height="200" VerticalAlignment="Top">
<TextBlock>Name</TextBlock>
<TextBox Text="{Binding NewPerson.Name, Mode=TwoWay}"></TextBox>
<TextBlock>About</TextBlock>
<TextBox Text="{Binding NewPerson.About, Mode=TwoWay}"></TextBox>
<Button VerticalAlignment="Top" Margin="30" Width="130" Click="Button_Click_1">Add</Button>
</StackPanel>
</StackPanel>
</Grid>