我想为我的viewmodel中的每个用户添加一个UserSontrol到ItemsControl。
这是带有ItemsControl的主窗口xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:UserControlSolution" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="UserControlSolution.MainWindow"
Title="MainWindow" Height="836" Width="270.5" Background="#FF232323" BorderBrush="{DynamicResource Border}" Loaded="Window_Loaded" >
<Window.Resources>
<LinearGradientBrush x:Key="Border" EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FF6C6C6C" Offset="0.009"/>
<GradientStop Color="#FFA1A1A1" Offset="1"/>
</LinearGradientBrush>
</Window.Resources>
<StackPanel Name="Container" Margin="0,10,0,0">
<ItemsControl x:Name="UserContainer" ItemsSource="{Binding allUserViewModel.Users}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:UserControlButton />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
代码背后:
using UserControlSolution.ViewModel;
using UserControlSolution.Models;
namespace UserControlSolution
{
public partial class MainWindow : Window
{
public AllUserViewModel allUserViewModel { get; set; }
public MainWindow()
{
InitializeComponent();
DwmDropShadow.DropShadowToWindow(this);
allUserViewModel = new AllUserViewModel();
allUserViewModel.AddUser(new User(1, "Robby", "Bezet"));
allUserViewModel.AddUser(new User(2, "Erwin", "Bezet"));
allUserViewModel.AddUser(new User(3, "Laurens", "Bezet"));
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Dock window to right side of the screen
AppBarFunctions.SetAppBar(this, ABEdge.Right);
this.DataContext = allUserViewModel;
}
}
}
视图模型:
using UserControlSolution.Models;
namespace UserControlSolution.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;
}
}
}
为什么运行此项时,ItemsControl中没有显示任何项目? 这是我第一次使用ItemsControl。
答案 0 :(得分:2)
将itemsSource绑定更改为ItemsSource="{Binding Users}">
,因为您窗口的DataContext
已经是alluserViewmodel