2

在我的WPFmvvm(light) 项目中,我遇到了这样的问题:绑定ListView.SelectedItem到 my后ModelView,我试图将其从.It 更改为 .ItModelView似乎没问题,但在 View 没有发生任何事情:

XAML:

<ListView SelectedItem="{Binding SelectedOne}" 
          ItemsSource="{Binding Items}">
</ListView>

<ListView     ScrollViewer.CanContentScroll="False"
              ItemsSource="{Binding Items}"
              ItemTemplateSelector="{StaticResource myDataTemplateSelector}"
              HorizontalContentAlignment="Stretch"
              SelectedItem="{Binding SelectedOne, Mode=TwoWay}"
              IsSynchronizedWithCurrentItem="True">
</ListView>

模型视图:

ObservableCollection<ItemViewModel> _EAItems = new ObservableCollection<ItemViewModel>();
public ObservableObject _selectedOne;

public ObservableCollection<ItemViewModel> Items
        {
            get
            {
                return _EAItems;
            }
            set
            {
                _EAItems = value;
            }
        }

public ObservableObject SelectedOne 
        {
            get { return _selectedOne; }
            set 
            {

                if(_selectedOne != value)
                _selectedOne = value;

            }
        }
Select = new RelayCommand(() => 
            {
                if (qw == 15) { qw = 0; }else
                SelectedOne = Items[qw];
                qw++;
            });

项目是ObservableCollection

我添加了另一个Listview并将其绑定到相同的源。当我更改SelctedItem其中一个时Listview,它会显示在另一个上,反之亦然。

我查看了很多类似的解决方案,但我不知道出了什么问题:(

4

3 回答 3

2

first you should also post the code for the binding for the ItemsSource, the ItemsSource property.

but the main problem is the you do not call PropertyChanged in your setter

    public ObservableObject SelectedOne 
    {
        get { return _selectedOne; }
        set 
        {

            if(_selectedOne != value)
            _selectedOne = value;

            OnPropertyChanged("SelectedOne ");//<-- otherwise the view dont know that the SelectedItem changed
        }
    }
于 2012-08-02T11:39:36.733 回答
2

In order to make the binding work you would have to raise a PropertyChanged event from the SelectedOne setter. The class that defines the SelectedOne property would have to implement INotifyPropertyChanged.

Regardless of the type of the SelectedOne property (even if it is itself an ObservableObject), you have to raise a PropertyChanged event when the value of the property changes.

于 2012-08-02T11:40:02.223 回答
1

我同意克莱门斯和盲人的观点。唯一的事实是 SelectedOne 需要与为 Collection 设置的类相同。对于 MVVM-light 库,该方法是 RaisePropertyChanged 而不是 OnPropertyChanged(如果您的 viewModel 继承自 ViewModelBase)。

如果您的源包含 ItemViewModels 应使用此代码:

private ItemViewModel _selectedOne;

public ItemViewModel SelectedOne 
{
    get { return _selectedOne; }
    set 
    {

        if(_selectedOne != value)
        _selectedOne = value;

        RaisePropertyChanged("SelectedOne");
    }
}

您的集合不需要 RaisePropertyChanged 的​​原因是 ObsvervableCollection 类已经以某种方式包含它。

问候,

凯文

于 2012-08-02T12:47:52.467 回答