通过绑定更新视图不​​起作用

时间:2011-10-24 21:20:14

标签: .net wpf xaml data-binding prism

使用带有Prism 4.0的MVVM更新列表框的布局时遇到问题。

我将observablecollection显示到我的列表框没有问题,但是当我将它绑定到DelegateCommand以添加新用户或更新选定的列表框项时,它不会更新,但基础对象正在更新。我尝试使用MessageBox.Show给我最近的输出,它做了更改,但在view.xaml它没有更新。

public class ProfileViewModel : DependencyObject
{
 public DelegateCommand SaveCommand { get; set; }
 public ObservableCollection<Persons> Persons { get; set; }

 public ProfileViewModel()
 {
   CreatePerson();
   SaveCommand = new DelegateCommand(Save,CanSave);
 }

 private void Save()
 {
   Person[0].LastUpdated = DateTime.Now
   Persons.Add(new Persons { FIrstName = "Bob", LastName "Bob," LastUpdated=DateTime.Now});
 }

 private bool CanSave()
 {
  return true;
 }

 public void CreatePerson()
 {
   this.Persons = new ObservableCollection<Persons>();
   Persons.Add(new Persons { FirstName = "John", LastName = "Doe", LastUpdated = DateTime.Now});Persons.Add(new Persons { FirstName = "John", LastName = "Doe", LastUpdated = DateTime.Now});
Persons.Add(new Persons { FirstName = "John", LastName = "Doe", LastUpdated = DateTime.Now});
 }
}
}

ProfilePage.Xaml

<ListBox ItemsSource="{Binding Persons}" Name="ListBoxItem">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Vertical">
                            <TextBlock Text="{Binding FirstName}"/>
                            <TextBlock Text="{Binding LastName}" />
                            <Button Content="_Save" Command={Binding Source={Static Resource ProfileViewModel{, Path=SaveCommand}" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

ProflilePage.xaml.cs

 public partial class ProfilePage : Window
 {
   private ProfileViewModel _vm;

   [Dependency]
   public ProfileViewModel VM
   {
     set { _vm = value; this.DataContext = _vm; }
   }

   public ProfilePage()
   {
     InitializeComponent();
   }

App.xaml.cs

protected override void OnStartup(StartupEventArgs e)
 {
   IUnityContainer container = new UnityContainer();
   ProfileViewModel source = new ProfileViewModel();
   ProfilePage window = container.Resolve<ProfilePage>();
   window.show();
 }

My Persons类实现了INotifyPropertyChanged,并具有LastName,FirstName和LastUpdated的getter setter。

2 个答案:

答案 0 :(得分:0)

我很确定你需要DataContextProxy才能使绑定工作。 ElementName绑定也适用于ListBox

答案 1 :(得分:0)

如果我正确地看待这个,你还需要在VM上实现INotifyPropertyChanged。 View无法查看从模型中触发的事件。