我有一个与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>
这是viewmodel
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; }
}
}
我还有一个存储所有UserViewModel的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?
答案 0 :(得分:2)
为了在列表框中显示usercontrol,您只需要为列表框定义ItemTemplate,如
<ListBox ItemsSource="{Binding Users}">
<ListBox.ItemTemplate>
<DataTemplate>
<local:UserControl1/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>