2016-05-06 34 views
0

Xamarin Forms XAMLでは、ViewCellが選択されていない場合、その一部を非表示にしたいと考えています。 たとえば、text = "2番目のラベルは"選択されている場合のみ表示します "。 MVVMをコードなしで使用する方法あなたのリストビューでXamarinフォームをカスタマイズする方法ListView SelectedItem ViewCell Visibility?

<ListView x:Name="listView"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout> <Label Text="Always Show it"/> <Label Text="Show only if selected" IsVisible={Binding somewhere?}/> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>

答えて

2

コードビハインドを含まないMVVMのアプローチがあります。別のプロパティの*のために持って、

public class ItemViewModel : INotifyPropertyChanged 
{ 
    ...... 

    private bool _isSelected; 
    public bool IsSelected 
    { 
     get { return _isSelected; } 
     set 
     { 
      if(_selectedItem != value) 
      { 
       _isSelected = value; 
       OnPropertyChanged(); 
      } 
     } 
    } 
} 

を次に、ページののviewmodelに:

のviewmodels

は、項目が現在選択されているかどうかを示す情報を格納するために、あなたのListView項目のviewmodelのプロパティ*を追加します。バインダーListViewSelectedItemは、それに応じてIsSelectedの値を設定することができます。

ビュー

バインドListView項目のviewmodelにIsVisibleプロパティ:

<Label Text="Show only if selected" IsVisible="{Binding IsSelected}"/> 

プロパティは INotifyPropertyChangedを実装したり、他の継承したクラスでは、公共の財産であることが必要*)

を実装しているクラスでは、上記のようにプロパティがプロパティ変更通知を発生させますスニペット。参考のため


  • Xamarin公式ガイド:Gist
+0

はい、私はそれを試して、正常に動作し、ありがとう。 –

+0

あなたはジャカルタの歓迎です。 :D – har07

+0

すばらしい仕事、54k。 –

0

各項目は「IsSelected」バインド可能なプロパティを持っている必要があります。リストビューでItemSelectedイベントがアイテムを取得し、IsSelectedがtrueに設定されます。新しい選択項目が押されたときにIsSelectedをfalseに設定できるように、現在選択されている項目の参照を保持するようにしてください。このように見えるはずです。

MyItem _currentlySelectedItem; 
    void OnSelection (object sender, SelectedItemChangedEventArgs e) 
    { 
     if (e.SelectedItem == null) { 
     _currentlySelectedItem = null; 
     return; //ItemSelected is called on deselection, which results in SelectedItem being set to null 
     } 
     var selectedItem = e.SelectedItem as MyItem; 
     selectedItem .IsSelected= true; 
    _currentlySelectedItem.IsSelected= false; /// Make sure to check for null 
    _currentlySelectedItem = selectedItem ; 
    } 
+0

で上記のコードのPart 5. From Data Bindings to MVVM

  • 完全な例は、WPFでAttachedPropertyのようにバインド可能なプロパティですか? –

  • +0

    @YohanesNurcahyo私はWPFを使用していないのでわからない。バインディングの仕組みを理解するには、https://developer.xamarin.com/guides/xamarin-forms/user-interface/xaml-basics/data_bindings_to_mvvm/を参照してください。 –

    +0

    BindablePropertyを作成する方法はたくさんありますが、これは私が使うべきですか? https://developer.xamarin.com/api/type/Xamarin.Forms.BindableProperty/ –

    関連する問題