我想在我的项目中开始使用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.
现在我发现的解决方案是向PersonViewModel添加IsChecked属性(虽然我并不真的需要它)并将其绑定到CheckBox IsChecked DependencyProperty,但后来我添加了一个让用户可以使用的功能按下一个按钮,它将迭代ListBox中的所有人,并将其IsChecked属性更改为true(按钮 - &gt;全选)。 在消失检查错误之后,我遇到了另一个错误,我认为它与某些消失的支票有关 - 我在检查和取消检查时触发的操作只会在您选择全部时触发某些CheckBox。 我试着计算当我使用select all函数时会发生多少次动作,我发现ListBox(当前可见CheckBoxes)的高度与触发的触发器数量之间存在连接,而且我滚动到中间ListBox并使用了SelectAll功能,触发器没有触发,直到循环遇到我可以在ListBox中看到的第一个可见的ChekBox。
如果你不尝试它,有点难以理解这个bug,所以请在这里发表评论。
提前致谢!
答案 0 :(得分:0)
简单的答案是:你反对当前。
绑定完全是为了改变ViewModel中的值,并允许您针对简单的视图模型类编写代码,以便您的表示逻辑没有业务逻辑。在您的示例中,执行AddToInvitation
RemoveFromInvitation
的决定在您的视图中,并且不应该存在。
您可以很好地使用bool IsInvited{get;set;}
属性轻松绑定到复选框(不需要依赖属性)。这将允许用户更改保留在视图模型中。如果您需要其他更复杂的逻辑,则应附加到ViewModel必须实现的PropertyChagned
事件形式INotifyPropertyChanged
接口。然后你可以随意改变你的简单类中的属性,ui将相应地更新。