【问题标题】:Bind CheckBoxes to LongListSelector将复选框绑定到 LongListSelector
【发布时间】:2013-04-06 13:53:11
【问题描述】:

我正在尝试在 LongListSelector 中绑定一些 CheckBox。它们绑定,并且在呈现视图时选中/取消选中正确的 CheckBox,但我无法通过选中/取消选中 CheckBox 来修改我的底层对象。

<Grid Grid.Row="3">
<phone:LongListSelector ItemsSource="{Binding PlaceOfInterestCategories}">
    <phone:LongListSelector.ItemTemplate>
        <DataTemplate>
            <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" Content="{Binding Name}"/>
        </DataTemplate>
    </phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>    

我的 ViewModel 中有以下代码:

private ObservableCollection<PlaceOfInterestCategory> _placeOfInterestCategories;

public ObservableCollection<PlaceOfInterestCategory> PlaceOfInterestCategories
{
    get { return _placeOfInterestCategories; }
    set
    {
        if (_placeOfInterestCategories != value)
        {
            _placeOfInterestCategories = value;

            OnPropertyChanged();
        }
    }
}

public event PropertyChangedEventHandler PropertyChanged;

[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    var handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

-

[DataContract]
public class PlaceOfInterestCategory
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public bool IsSelected { get; set; }
}

我尝试订阅 CollectionChanged 事件,但它没有被触发。

我总是可以在我的代码隐藏中处理 Checked 和 Unchecked,但我不想这样做,而是在我的视图模型中处理所有内容。

对于如何让绑定正常工作的任何意见,我将不胜感激。

【问题讨论】:

  • 你能发布你的 PlaceOfInterestCategory 课程吗?
  • 没有必要为你的标题添加标签,有一个标签系统。请阅读meta.stackexchange.com/q/19190 进行讨论。同样,由于您的角色卡在右下角,“谢谢”已经被“覆盖”了,所以也不需要。

标签: xaml mvvm windows-phone-8 2-way-object-databinding


【解决方案1】:

使 PlaceOfInterestCategory 实现 INotifyPropertyChange 并在属性设置器中调用 OnPropertyChanged()。当您在视图中绑定到可观察集合的项目时,它们是 PlaceOfInterestCategory,它们应该实现INPC。您是否尝试在设置器中设置断点以查看在您检查复选框时属性是否实际更新?是没有设置它们还是没有反映在您的 UI 中?

【讨论】:

  • 非常感谢!我的印象是 ObservableCollection 为我处理了 INPC,但这仅适用于简单类型,事后看来这很有意义。
猜你喜欢
  • 1970-01-01
  • 2014-01-12
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-14
  • 1970-01-01
  • 2014-05-30
相关资源
最近更新 更多