UserViewModel とバインドする UserControl があります
これは私の簡略化された UserControlButton です
<UserControl
x:Class="UserControlSolution.UserControlButton"
x:Name="UserControl"
>
<Grid x:Name="LayoutRoot" Height="50" RenderTransformOrigin="0.5,0.5" VerticalAlignment="Top" HorizontalAlignment="Stretch">
<StackPanel x:Name="UserContainer" Orientation="Vertical" VerticalAlignment="Center" Grid.Column="1" Background="{DynamicResource DarkGrey}">
<TextBlock x:Name="NameLabel" FontSize="16" Foreground="#FFE5E5E5" Text="{Binding Name}" VerticalAlignment="Top" FontFamily="Segoe UI Semibold" RenderTransformOrigin="0.5,0.5" Margin="0,0,0,2"/>
<TextBlock x:Name="UserStatusLabel" Text="{Binding UserStatus}" TextWrapping="NoWrap" VerticalAlignment="Top" Foreground="#FFE5E5E5" />
</StackPanel>
</Grid>
</UserControl>
これがビューモデルです
public class UserViewModel : BaseViewModel
{
readonly User _user;
public UserViewModel(User user)
{
if (user == null)
throw new ArgumentNullException("User");
_user = user;
}
public string Name
{
get { return _user.Name; }
set
{
if (value == _user.Name)
return;
_user.Name = value;
NotifyPropertyChanged("UserName");
}
}
public string UserStatus
{
get { return _user.UserStatus; }
set
{
if (value == _user.UserStatus)
return;
_user.UserStatus = value;
NotifyPropertyChanged("UserStatus");
}
}
public int ID
{
get { return _user.ID; }
}
}
すべての UserViewModels を格納する ViewModel もあります
public class AllUserViewModel : BaseViewModel
{
ObservableCollection<UserViewModel> _users;
public AllUserViewModel()
{
Users = new ObservableCollection<UserViewModel>();
}
/// <summary>
/// Observable Collection of Users
/// Uses INotifyPropertyChange when list changes
/// </summary>
public ObservableCollection<UserViewModel> Users
{
get { return _users; }
set
{
if (_users != value)
{
_users = value;
NotifyPropertyChanged("Users");
}
}
}
public void AddUser(User user)
{
UserViewModel userViewModel = new UserViewModel(user);
Users.Add(userViewModel);
}
public UserViewModel GetUser(int ID)
{
foreach (UserViewModel u in Users)
{
if(u.ID == ID)
return u;
}
return null;
}
}
次に、メインウィンドウで AllUserViewModel を埋めます (テスト用)。
public AllUserViewModel allUserViewModel { get; set; }
public MainWindow()
{
InitializeComponent();
DwmDropShadow.DropShadowToWindow(this);
allUserViewModel = new AllUserViewModel();
Robby = new User(1, "Robby", "Calling");
Kevin = new User(2, "Kevin", "Calling");
Laurens = new User(3, "Laurens", "Calling");
Erwin = new User(4, "Erwin", "Calling");
allUserViewModel.AddUser(Robby);
allUserViewModel.AddUser(Kevin);
allUserViewModel.AddUser(Laurens);
allUserViewModel.AddUser(Erwin);
this.DataContext = allUserViewModel;
}
問題は、AllUserViewModel コレクションの各 UserViewModel に UserControlButton を追加するにはどうすればよいかということです。