我有一个 UserControl,我想在 MainWindow 上多次加载它。为此,我使用ItemsControl
:
<ItemsControl Grid.Row="1"
ItemsSource="{Binding FtpControlList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"
IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type my:BackUpControl}">
<my:BackUpControl Margin="5"
Width="500" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我的 UserControl 由 ViewModel 绑定。我的 MainWindow 也有一个 ViewModel。在 MainWindowViewModel 中,我有一个 OberservableCollection 依赖属性,其中包含我的 UserControlViewModel 列表。在 MainWindowViewModel 的构造函数中,我将一些 UserControlViewModels 添加到列表中。
public MainWindowViewModel()
{
FtpControlList = new ObservableCollection<BackUpControlViewModel>();
FtpControlList.Add(new BackUpControlViewModel("View 1"));
FtpControlList.Add(new BackUpControlViewModel("View 2"));
FtpControlList.Add(new BackUpControlViewModel("View 3"));
}
public static readonly DependencyProperty FtpControlListProperty = DependencyProperty.Register("FtpControlList", typeof(ObservableCollection<BackUpControlViewModel>), typeof(MainWindowViewModel));
public ObservableCollection<BackUpControlViewModel> FtpControlList
{
get { return (ObservableCollection<BackUpControlViewModel>)GetValue(FtpControlListProperty); }
set { SetValue(FtpControlListProperty, value); }
}
现在由于某种原因,它加载了 3 次空用户控件,而不是 FtpControlList 属性中的那些,属性设置为“视图 1、视图 2 和视图 3”。如何确保列表中的 UserControls 已加载而不是空的?
UserControlViewModel 的一部分:
// part of the UserControl Viewmodel
public BackUpControlViewModel()
{
}
public BackUpControlViewModel(string header)
{
GroupBoxHeader = header;
}
#region Dependency Properties
public static readonly DependencyProperty GroupBoxHeaderProperty = DependencyProperty.Register("GroupBoxHeader", typeof(string), typeof(BackUpControlViewModel), new UIPropertyMetadata("empty"));
public string GroupBoxHeader
{
get { return (string)GetValue(GroupBoxHeaderProperty); }
set { SetValue(GroupBoxHeaderProperty, value); }
}
public static readonly DependencyProperty FtpUrlProperty = DependencyProperty.Register("FtpUrl", typeof(string), typeof(BackUpControlViewModel), new UIPropertyMetadata("ftpurl"));
public string FtpUrl
{
get { return (string)GetValue(FtpUrlProperty); }
set { SetValue(FtpUrlProperty, value); }
}
public static readonly DependencyProperty FtpUserProperty = DependencyProperty.Register("FtpUser", typeof(string), typeof(BackUpControlViewModel), new UIPropertyMetadata("ftpUser"));
public string FtpUser
{
get { return (string)GetValue(FtpUserProperty); }
set { SetValue(FtpUserProperty, value); }
}
#endregion
这可能是一些愚蠢的事情,但我似乎找不到它。MainWindow 和 UserControl 的数据上下文绑定到它的 Viewmodel。
编辑:BackupControl datacontext 设置为 BackupControlViewModel(回答 Rachel 的问题)
public partial class BackUpControl : UserControl
{
public BackUpControl()
{
InitializeComponent();
this.DataContext = new BackUpControlViewModel();
}
}