RaisePropertyChanged不适用于ObservableCollection

时间:2013-05-30 19:09:50

标签: mvvm listbox mvvm-light observablecollection

使用MVVM Light Toolkit进行更新UI时,我遇到了一个非常奇怪的问题。对于我的ObservableCollection,RaisePropertyChanged根本不起作用。

以下是XAML代码:

<ListBox x:Name="list"  ItemsSource="{Binding ModelList}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}">
       <ListBox.ItemTemplate>
           <DataTemplate>
               <StackPanel Orientation="Horizontal">
                   <TextBlock Text="{Binding Name}"></TextBlock>
                   <CheckBox IsChecked="{Binding IsChecked}"></CheckBox>
               </StackPanel>
           </DataTemplate>
       </ListBox.ItemTemplate>
       <interaction:Interaction.Triggers>
           <interaction:EventTrigger EventName="SelectionChanged">
                <cmd:EventToCommand Command="{Binding TempCommand}" CommandParameter="{Binding ElementName=list, Path=SelectedItem}"
                               PassEventArgsToCommand="True"/>
            </interaction:EventTrigger>
       </interaction:Interaction.Triggers>
   </ListBox>

还有ViewModel代码部分:

private Model _selectedItem;
    public Model SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            _selectedItem = value;
            RaisePropertyChanged("SelectedItem");
        }
    }

    private ObservableCollection<Model> _modelList;
    public ObservableCollection<Model> ModelList
    {
        get { return _modelList; }
        set
        {
            _modelList = value;
            RaisePropertyChanged("ModelList");
        }
    }

    public RelayCommand<Model> TempCommand { get; private set; }
    /// <summary>
    /// Initializes a new instance of the MainViewModel class.
    /// </summary>
    public MainViewModel()
    {
        modelList = new ObservableCollection<Model>()
            {
                new Model()
                    {
                        IsChecked = true,
                        Name = "Temp1"
                    },
                new Model()
                    {
                        IsChecked = false,
                        Name = "Temp2"
                    },
                new Model()
                    {
                        IsChecked = false,
                        Name = "Temp3"
                    }
            };
        ModelList = modelList;

        TempCommand = new RelayCommand<Model>(Model_SelectedItem);
    }

    private void Model_SelectedItem(Model item)
    {
        // What should I do here?
    }

当我更改ModelList时 - ListBox UI没有任何反应。

任何人都可以帮助我?

1 个答案:

答案 0 :(得分:2)

问题解决了。

当您在ObservableCollection或List中有自定义类时,它必须从ObservableObject派生,并且所有属性都必须触发RaisePropertyChanged事件。