【发布时间】:2011-12-14 11:47:41
【问题描述】:
我在使用 MVVM 和 Prism 4.0 更新列表框布局时遇到问题。
我没有问题将我的 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>
ProfilePage.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();
}
我的 Persons 类实现了 INotifyPropertyChanged,并有一个 LastName、FirstName 和 LastUpdated 的 getter setter。
【问题讨论】:
-
你能多贴一点代码吗?您拥有的 Listbox 代码与 VM 或 Person 类不匹配。
-
很抱歉,我的视图复制粘贴错误。已更新。
标签: .net wpf xaml data-binding prism