1

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

这是 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 没有反应。

任何人都可以帮助我吗?

4

1 回答 1

2

问题解决了。

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

于 2013-06-27T09:17:20.483 回答