2011-07-12 83 views
2

好吧,我的程序簡而言之有一個客戶列表。這些客戶都列在列表框中,所以當點擊他們的所有信息時,就會出現在表單上。這通過數據綁定起作用,頁面上的所有控件都綁定到列表框的selectedItem。WPF列表框命令

我現在想要做的是有一個消息對話框,詢問用戶在嘗試更改選擇時是否想要保存。如果他們不這樣做,我想將它恢復到集合中的原始項目。如果他們擊中取消,我想讓選擇重新回到先前選擇的項目。我想知道以MVVM方式完成此操作的最佳方式是什麼?

目前我有一個適合我的客戶的模型,我的虛擬機填充了列表框綁定的客戶集合。那麼是否有辦法處理虛擬機上的選擇更改事件,其中包括能夠操縱列表框的selectedIndex? 這是我的代碼,所以你可以看到我在做什麼。

   if (value != _selectedAccount) 
       { 
        MessageBoxResult mbr = MessageBox.Show("Do you want to save your work?", "Save", MessageBoxButton.YesNoCancel); 
        if (mbr == MessageBoxResult.Yes) 
        { 
         //Code to update corporate 
         Update_Corporate(); 
         _preSelectedAccount = value; 
         _selectedAccount = value; 
        } 
        if (mbr == MessageBoxResult.No) 
        { 
         //Do Stuff 

        } 
        if (mbr == MessageBoxResult.Cancel) 
        { 

         SelectedAccount = _preSelectedAccount; 
         NotifyPropertyChanged("SelectedAccount"); 
        } 

       } 

回答

1

XAML:

<ListBox ItemsSource="{Binding Customers}" SelectedItem="{Binding SelectedCustomer}" DisplayMemberPath="CustomerName"/> 

視圖模型:

private Customer selectedCustomer; 
public Customer SelectedCustomer 
{ 
    get 
    { 
    return selectedCustomer; 
    } 
    set 
    { 
    if (value != selectedCustomer) 
    { 
     var originalValue = selectedCustomer; 
     selectedCustomer = value; 
     dlgConfirm dlg = new dlgConfirm(); 
     var result = dlg.ShowDialog(); 
     if (!result.HasValue && result.Value) 
     { 
     Application.Current.Dispatcher.BeginInvoke(
      new Action(() => 
      { 
       selectedCustomerr = originalValue; 
       OnPropertyChanged("SelectedCustomer"); 
      }), 
      System.Windows.Threading.DispatcherPriority.ContextIdle, 
      null 
     ); 
     } 
     else 
     OnPropertyChanged("SelectedCustomer"); 
    } 
    } 
} 

here兩者/進一步信息。

+0

我的解決方案看起來很相似,我有一個問題。當用戶按下取消時,我希望選擇保持在原來的位置,並且我可以這樣做,但視圖突出顯示用戶點擊的項目,但表單其餘部分的所有帳戶信息都保持爲取消狀態。 –

+0

hmm,看起來像你需要使用調度器返回並更改selectedindex後更改爲原始。上面的代碼更新,以反映這一點,更多信息[這裏](http://blog.alner.net/archive/2010/04/25/cancelling-selection-change-in-a-bound-wpf-combo-box.aspx )。 –

+0

非常感謝鏈接,我閱讀了關於該帖子的評論,並最終使用了使用CollectionViewSource發佈在其下的另一種方法。只是想提一下,如果我把IsAsync屬性設置爲true,就可以使用上面的方法工作,但似乎很慢。 –

2

你能趕上變化的情況下最好的辦法是到ListBox的的SelectedItem綁定到另一個屬性在您的視圖模型,然後在一組,你可以做你需要做什麼:

private Customer selectedCustomer; 
public Customer SelectedCustomer 
{ 
    get { return selectedCustomer; } 
    set 
    { 
     if (selectedCustomer== value) return; 
     selectedCustomer = value; 
     RaisePropertyChanged("SelectedCustomer"); 
     // Do your stuff here 
    } 
} 

這是一個使用MVVM光源(RaisePropertyChanged)的例子。