2017-07-14 54 views
0

尝试创建将项目添加到列表的简单应用程序。使用ViewModel中的属性绑定条目时遇到问题。无法在双向模式下绑定条目和属性

这是我的XAML:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
     xmlns:viewModels="clr-namespace:MyScoreDemo.ViewModels;assembly=MyScoreDemo" 
     x:Class="MyScoreDemo.Views.ClubListPage"> 
<StackLayout 
    Padding="15" 
    Spacing="10"> 

    <Grid> 

     <Grid.RowDefinitions> 
      <RowDefinition Height="Auto"/> 
      <RowDefinition Height="Auto"/> 
      <RowDefinition Height="Auto"/> 
     </Grid.RowDefinitions> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="*"/> 
      <ColumnDefinition Width="*"/> 
     </Grid.ColumnDefinitions> 

     <Label Text="Name:" Grid.Row="0" Grid.Column="0"/> 
     <Entry x:Name="EntryName" Text="{Binding Club.Name, Mode=OneWayToSource}" Grid.Row="0" Grid.Column="1"/> 

     <Label Text="Country:" Grid.Row="1" Grid.Column="0"/> 
     <Entry x:Name="EntryCountry" Text="{Binding Club.Country, Mode=OneWayToSource}" Grid.Row="1" Grid.Column="1"/> 

     <Button Text="Add" Command="{Binding AddCommand}" CommandParameter="{x:Reference EntryName}" 
       Grid.Row="2" Grid.ColumnSpan="2" Grid.Column="0" /> 

    </Grid> 

    <ListView ItemsSource="{Binding Clubs}" 
       Margin="5"> 
     <ListView.ItemTemplate> 
      <DataTemplate> 
       <ViewCell> 
        <Grid> 
         <Grid.ColumnDefinitions> 
          <ColumnDefinition Width="*"/> 
          <ColumnDefinition Width="*"/> 
         </Grid.ColumnDefinitions> 

         <Label Text="{Binding Path=Name}"/> 
         <Label Text="{Binding Path=Country}" Grid.Column="1"/> 
        </Grid> 
       </ViewCell> 
      </DataTemplate> 
     </ListView.ItemTemplate> 
    </ListView> 

    <StackLayout.BindingContext> 
     <viewModels:ClubListViewModel/> 
    </StackLayout.BindingContext> 

</StackLayout> 

和视图模型代码:

private Club _club; 
    public ICommand AddCommand { get; set; } 
    public ICommand RemoveCommand { get; set; } 

    public event PropertyChangedEventHandler PropertyChanged; 

    public ObservableCollection<Club> Clubs { get; set; } 

    public ClubListViewModel() 
    { 
     AddCommand = new Command(AddClub); 
     RemoveCommand = new Command(RemoveClub); 
     Clubs = new ObservableCollection<Club>(); 
    } 

    public Club Club 
    { 
     get => _club; 
     set 
     { 
      _club = value; 
      OnPropertyChanged("Club"); 
     } 
    } 

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 

    //Commands 
    private void AddClub() 
    { 
    } 

在property`s设置断点设置俱乐部部分和尝试不同的模式,但它永远不会停止。

+0

where'DataContext'? –

+0

问题是xaml的一部分。数据上下文在xaml文件的末尾。 – Max

+0

你可以粘贴那部分?因为'DataContext'很重要 –

回答

0

我需要改变的只是在我的ViewModel类的构造函数中添加了Club = new Club();