У меня есть исключение: Items
коллекция должна быть пустой перед использованием ItemsSource
при использовании UserControl
с DataGrid
.
<Window.Resources>
<DataTemplate DataType="{x:Type login:LoginViewModel}">
<login:LoginView />
</DataTemplate>
<DataTemplate DataType="{x:Type customers:CustomerListViewModel}">
<customers:CustomerListView />
</DataTemplate>
<DataTemplate DataType="{x:Type customers:CustomerDetailsViewModel}">
<customers:CustomerDetailsView />
</DataTemplate>
<DataTemplate DataType="{x:Type customers:CustomerItemsViewModel}">
<customers:CustomerItemsView />
</DataTemplate>
<DataTemplate DataType="{x:Type finishedProductLots:FinishedProductListViewModel}">
<finishedProductLots:FinishedProductListView />
</DataTemplate>
<DataTemplate DataType="{x:Type finishedProductLots:FinishedProductLotDetailViewModel}">
<finishedProductLots:FinishedProductLotDetailView />
</DataTemplate>
<DataTemplate DataType="{x:Type supplierLots:SupplierLotListViewModel}">
<supplierLots:SupplierLotListView />
</DataTemplate>
<DataTemplate DataType="{x:Type supplierLots:SupplierLotDetailViewModel}">
<supplierLots:SupplierLotDetailView />
</DataTemplate>
<DataTemplate DataType="{x:Type Users:UserViewModel}">
<Users:UserView />
</DataTemplate>
<DataTemplate DataType="{x:Type InternalLot:InternalLotListViewModel}">
<InternalLot:InternalLotListView />
</DataTemplate>
</Window.Resources>
<Grid Grid.Column="0" Grid.Row="1" MinHeight="20">
<ContentControl Name="Content" Content="{Binding CurrentViewModel}"/>
</Grid>
С помощью этой настройки я могу изменить представление в моем главном окне в коде, установив свойство CurrentViewModel.
Теперь у меня появилась идея создать модель представления-представления с помощью DataGrid
(и функции поиска), которую я мог бы использовать во всем приложении.
Итак, я создал UserControl
<UserControl x:Class="CustomerTracebility.UI.InternalLot.InternalLotListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CustomerTracebility.UI.InternalLot"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<ei:CallMethodAction TargetObject="{Binding}" MethodName="LoadInternalLots" />
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Grid Grid.Row="0">
<StackPanel Orientation="Horizontal">
<Label Content="Lotnumber"></Label>
<!--<TextBox MinWidth="100" Text="{Binding LotFilterValue}"></TextBox>-->
<Button Content="Apply"></Button>
</StackPanel>
</Grid>
<Grid Grid.Row="1">
<DataGrid ItemsSource="{Binding InternalLots}"
AutoGenerateColumns="False"
CanUserAddRows="False"
IsReadOnly="True"
>
<!--<DataGrid.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick"
Command="{Binding Path=ViewFinishedProductLotCommand}"
CommandParameter="{Binding SelectedFinishedProductLot}" />
</DataGrid.InputBindings-->>
<!--<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="View"
Command="{Binding DataContext.ViewFinishedProductLotCommand, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"
CommandParameter="{Binding SelectedFinishedProductLot}"/>
<MenuItem Header="Trace"
Command="{Binding DataContext.TraceCommand, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"
CommandParameter="{Binding SelectedFinishedProductLot}"/>
<MenuItem Header="Transmit"
CommandParameter="{Binding ElementName=fpLotDataGrid, Path=SelectedItems}"
Command="{Binding DataContext.SendCommand, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"
ToolTip="Send the selected batches to the customer(s)"/>
--><!--CommandParameter="{Binding ElementName=fpLotDataGrid, Path=SelectedItems}"--><!--
</ContextMenu>-->
<!--</DataGrid.ContextMenu>-->
<DataGrid.Columns>
<!-- 
 -->
<DataGridTextColumn Binding="{Binding LotNumber}"
Width="*"
Header="Lot
Number"
/>
<DataGridTextColumn Binding="{Binding ItemNumber}"
Width="*"
Header="Item
Number"
/>
<DataGridTextColumn Binding="{Binding Item.Description}"
Width="*"
Header="Item Description" />
<DataGridTextColumn Binding="{Binding ExpiryDate, StringFormat='dd-MM-yyyy'}"
Width="*"
Header="Expiry
Date"/>
<DataGridTextColumn Binding="{Binding HarvestDate, StringFormat='dd-MM-yyyy'}"
Width="*"
Header="Harvest
Date" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Grid>
И я пытаюсь вызвать его с другого пользовательского элемента управления
<UserControl x:Class="CustomerTracebility.UI.FinishedProductLots.FinishedProductLotDetailView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CustomerTracebility.UI.FinishedProductLots"
mc:Ignorable="d"
d:DesignHeight="600" d:DesignWidth="600">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="7">
<ContentControl Name="Content" Content="{Binding InternalLotListViewModel}"/>
</Grid>
</Grid>
</UserControl>
И мой код позади
private ObservableCollection<Lot> _InternalLots;
public ObservableCollection<Lot> InternalLots
{
get { return _InternalLots; }
set { SetProperty(ref _InternalLots, value); }
}
public async void LoadInternalLots()
{
List<Lot> list;
if (this.LotFilterValue == string.Empty)
{
list = await this.lotBll.GetLotNumbersWithFilter();
}else
{
list = await this.LotBll.GetLotNumbersWithFilter(this.LotFilterValue);
}
if(list.Count > 33)
{
this.InternalLots = new ObservableCollection<Lot>();
foreach (var i in list.GetRange(0, 33))
{
InternalLots.Add(i);
}
//this.InternalLots = new ObservableCollection<Lot>();
}
else
{
this.InternalLots = new ObservableCollection<Lot>();
foreach (var i in list)
{
InternalLots.Add(i);
}
}
}
Итак, резюмируем:
Мое главное окно имеет UserControl
, которое устанавливается в коде позади. в Xmal этого представления есть UserControl
, который устанавливается таким же образом. (загруженная функция срабатывает при загрузке элемента управления). Но когда я заполняю свою наблюдаемую коллекцию, я получаю сообщение об ошибке Items
коллекция должна быть пустой перед использованием ItemsSource
Я искал свою ошибку, но не могу ее найти, и у меня действительно нет понятия, где искать ...