我在這裏猜測,因爲你的問題有點模糊,你不太清楚如何將這些碎片鉤在一起。爲了簡單起見,讓我們直接將ViewModel掛接到用戶控件並將其全部綁定。
只要您的視圖模型中填充了正確的人員集合,下面的所有綁定都將處理數據並顯示正確的數據。記下組合框中所選項目的雙向綁定。這允許WPF將新選擇的項目發送回視圖模型。
在用戶控件的代碼背後:
public MyUserControl()
{
DataContext = new MyViewModel();
}
在用戶控件的XAML:
<ComboBox ItemsSource="{Binding AllPeople}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />
<TextBox Text="{Binding SelectedItem.LastName}" />
<TextBox Text="{Binding SelectedItem.FirstName}" />
<TextBox Text="{Binding SelectedItem.EmailName}" />
您的視圖模型:
private IEnumerable<Person> _allPeople;
public IEnumerable<Person> AllPeople
{
get { return _allPeople; }
set
{
if (_allPeople != value)
{
_allPeople = value;
NotifyPropertyChanged("AllPeople");
}
}
}
private Person _selectedItem;
public Person SelectedItem
{
get { return _selectedItem; }
set
{
if (!_selectedItem != value)
{
_selectedItem = value;
NotifyPropertyChanged("SelectedItem");
}
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName);
}
}
}
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
我想你需要澄清你的問題多一點,你說您使用MVVM,那麼您在樣本中面臨的限制是什麼? – 2009-07-26 00:24:20