Я создал ObservableCollection для заполнения ListViev из базы данных, используя структуру сущностей.Когда я вызываю метод fill, я оказываюсь в бесконечной попытке заполнить коллекцию.У меня есть модель Device_compiexity и Device_category, которые связаны с device_complexity_id.Для них я создал VievModel, на основе которого я создал заполненную коллекцию.
Моя ViewModel:
class DeviceCategoryViewModel
{
TechDContext dc = new TechDContext();
public int Device_category_id { get; set; }
public string Сategory_name { get; set; }
public int Device_complexity_id { get; set; }
public string Device_complexity_name { get; set; }
public static DeviceCategoryViewModel DeviceCaterogyVM(DeviceCategory deviceCategory, DeviceComplexity deviceComplexity)
{
return new DeviceCategoryViewModel
{
Device_category_id = deviceCategory.Device_category_id,
Сategory_name = deviceCategory.Category_name,
Device_complexity_id = deviceCategory.Device_complexity_id,
Device_complexity_name = deviceComplexity.Device_complexity_name,
};
}
public DeviceCategoryViewModel()
{
FillDeviceCategories();
}
public void FillDeviceCategories()
{
using (TechDContext dc = new TechDContext())
{
var q = from cat in dc.DeviceCategories
join com in dc.DeviceComplexities on cat.Device_complexity_id equals com.Device_complexity_id
select new DeviceCategoryViewModel
{
Device_category_id = cat.Device_category_id,
Сategory_name = cat.Category_name,
Device_complexity_id = com.Device_complexity_id,
Device_complexity_name = com.Device_complexity_name
};
deviceCategories = new ObservableCollection<DeviceCategoryViewModel>(q);
}
}
private ObservableCollection<DeviceCategoryViewModel> deviceCategories;
public ObservableCollection<DeviceCategoryViewModel> DeviceCategories
{
get
{
return deviceCategories;
}
}
private static DeviceCategoryViewModel selectedDeviceCategory;
public DeviceCategoryViewModel SelectedDeviceCategory
{
get
{
return selectedDeviceCategory;
}
set
{
selectedDeviceCategory = value;
}
}
}
При инициализации в окне я делаю:
DeviceCategoriesPanel.DataContext = new DeviceCategoryViewModel();
В XAML я делаю это:
<Grid HorizontalAlignment="Left" Height="447" x:Name="DeviceCategoriesPanel" Margin="392,2,0,0" VerticalAlignment="Top" Width="392">
<Label x:Name="label1_Copy2" Content="Категории устройств" HorizontalAlignment="Left" Margin="10,0,0,410" VerticalAlignment="Bottom" FontWeight="Bold" Width="188" FontSize="14"/>
<ListView x:Name="categoriesComponentsLV" HorizontalAlignment="Right" MaxHeight="200" MinHeight="150" Margin="0,44,10,0" Grid.Column="0" ItemsSource="{Binding DeviceCategories}" SelectedItem="{Binding SelectedDeviceCategory}" VerticalAlignment="Top" Width="372" Height="197">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Margin="5">
<TextBlock FontSize="18" Text="{Binding Path=Category_name}" />
<TextBlock Text="{Binding Path=Device_complexity_name}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>