0

プロジェクトでMVVMの使用を開始したいので、調査を開始しました。WPF で少し遊んでいるときに、インターネットを探索しているときに自分で解決策を見つけることができないというバグに遭遇しました。

私はそのようなものを持っています(同じネットワークにないため、完全なコードを貼り付けることができません):

MainView.Xaml

<ListBox ItemsSource="{Binding Persons}">
 <ListBox.ItemTemplate>
  <DataTemplate>
   <CheckBox Content="{Binding Name}">
    <i:Interaction.Triggers>
     <i:EventTrigger EventName="Checked">
        <my:AddToInvitation />
     </i:EventTrigger>
     <i:EventTrigger EventName="Unchecked">
        <my:RemoveFromInvitation />
     </i:EventTrigger>
    </i:Interaction.Triggers>
   </CheckBox>
  </DataTemplate>
</ListBox.ItemTemplate>

MainViewModel.cs

public ObservableCollection<PersonViewModel> Persons { get; set; }

public MainViewModel()
{
  this.Persons = new ObservableCollection<PersonViewModel>();
  for(int i=0;i<1000;i++)
  {
     PersonViewModel personVM = new PersonViewModel (string.Format("Person - {0}",i));
     this.Persons.add(personVM);
  }
}

PersonViewModel.cs

private Person PersonObject { get; set; }

public string Name
{
  get
  {
     return this.PersonObject.Name;
  }
}

public PersonViewModel(string personName)
{
  this.PersonObject = new Person(personName);
}

Person.cs

public string Name { get; set; }

public Person(string name)
{
   this.Name = name;
}

これを貼り付けて実行すると、問題なく表示されます。問題は、次の手順を試すときです。

1) Check the first 10 persons in the ListBox.
2) Scroll down the ListBox to the bottom of it.
3) Leave the mouse when the list box is scrolled down.
4) Scroll back up to the top of the ListBox.
5) Poof! you'r checking disappeared.

今私が見つけた解決策は、IsCheckedプロパティ(実際には必要ありませんが)をPersonViewModelに追加し、それをCheckBox IsChecked DependencyPropertyにバインドすることですが、ユーザーがボタンを押すことができる機能を追加しましたListBox 内のすべての人を繰り返し処理し、IsChecked プロパティを true (ボタン -> すべて選択) に変更します。消えるチェックのバグに続いて、消えるチェックに何らかの形で関連していると思われる別のバグを交差させました-チェックとチェック解除が発生したときにトリガーするように設定したアクションは、すべてを選択すると一部のチェックボックスに対してのみトリガーされます。

このバグはやってみないとわかりにくいので、試した人だけコメントしてください。

前もって感謝します!

4

1 に答える 1

0

簡単な答えは次のとおりです。あなたは流れに逆らっています。

バインディングとは、ViewModel の値を変更し、単純なビュー モデル クラスに対してコードを記述して、プレゼンテーション ロジックにビジネス ロジックが含まれないようにすることです。あなたの例では、実行する決定 AddToInvitation RemoveFromInvitationはあなたの見解にあり、そこにあるべきではありません。

チェックボックスに簡単にバインドできるプロパティが得意ですbool IsInvited{get;set;}(依存関係プロパティは必要ありません)。これにより、ユーザーの変更をビュー モデルに永続化できます。他のより複雑なロジックが必要な場合は、ViewModel が実装する必要があるPropertyChagnedイベント フォームインターフェイスにアタッチする必要があります。INotifyPropertyChanged次に、単純なクラスのプロパティを自由に変更でき、それに応じて ui が更新されます。

于 2012-10-29T08:41:56.890 に答える