2011-10-24 4 views
0

MVVMとPrism 4.0を使用してリストボックスのレイアウトを更新する際に問題があります。バインディングdoesntの作業を通してビューを更新する

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(); 
} 

私のPersonsクラスはINotifyPropertyChangedを実装しており、LastName、FirstName、LastUpdatedのゲッターセッターを持っています。

+0

もう少しコードを投稿できますか?あなたが持っているリストボックスのコードは、VMまたはPersonクラスと一致しません。 – JMcCarty

+0

申し訳ありませんが、間違ったコピーを貼り付けています。更新しました。 –

答えて

0

バインディングを動作させるには、DataContextProxyが必要です。 ElementNameバインディングもListBoxで動作します

+0

ElementNameバインディングを使用する場合は、MVVMパターンの規則を破っています。 –

+0

パターンの奴隷にならないでください。 =) – Yatrix

+0

これはパターンの奴隷ではなく、ソフトウェアアーキテクトと呼ばれています。規則を破るために実装するための小さなシステムを作ってはいけません。 –

0

これを正しく見ていれば、VMでもINotifyPropertyChangedを実装する必要があります。ビューは、モデルから発生したイベントを見ることはできません。

+0

それは動作しません。私はINotifyPropertyChangedとOnPropertyChangedを起動し、ObservableCollectionの Personsプロパティを渡しました。何も変更されていません。 –

関連する問題