You should use ViewModel as a DataContext for the XAML. Bind all of your controls to corresponding data source from ViewModel.
Step-1: Create a class and implement INotifyPropertyChanged
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Step-2: Create object
public class UserType
{
public int PKID { get; set; }
public string Name { get; set; }
}
Step-3: Create your own ViewModel class and implement previous class(BaseViewModel) and all other properties you want to bind to XAML.
public class ItemViewModel : BaseViewModel
{
public ItemViewModel()
{
this.LoadDatas();
}
private List<UserType> _userTypes;
public List<UserType> UserTypes
{
get { return _userTypes; }
set
{
_userTypes = value;
base.OnPropertyChanged("UserTypes");
}
}
private int _userTypeID;
public int UserTypeID
{
get { return _userTypeID; }
set
{
_userTypeID = value;
base.OnPropertyChanged("UserTypeID");
}
}
private void LoadDatas()
{
UserTypes = new List<UserType>()
{
new UserType { PKID=1, Name="Standard"},
new UserType { PKID=2, Name="Premium"}
};
}
}
Step-4: Import namespace into xaml
xmlns:vm="clr-namespace:WpfApplication1"
Step-5: Bind your DataContext with your ViewModel
<Window.DataContext>
<vm:ItemViewModel />
</Window.DataContext>
Step-6: Create your control and bind with specific properties
<ComboBox Name="cboUserType" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5" Width="250" Height="25" ItemsSource="{Binding UserTypes, Mode=OneWay}" SelectedValue="{Binding UserTypeID}" SelectedValuePath="PKID" DisplayMemberPath="Name" />