Piszę aplikację w WPF, używając zestawu narzędzi MVVm i mam problem z podpięciem viewmodelu i widoku.Jak ustawić datacontext formantu użytkownika
Model jest tworzony z wykorzystaniem struktury eno.net.
ViewModel:
public class CustomerViewModel
{
private Models.Customer customer;
//constructor
private ObservableCollection<Models.Customer> _customer = new ObservableCollection<Models.Customer>();
public ObservableCollection<Models.Customer> AllCustomers
{
get { return _customer; }
}
private Models.Customer _selectedItem;
public Models.Customer SelectedItem
{
get { return _selectedItem; }
}
public void LoadCustomers()
{
List<Models.Customer> list = DataAccessLayer.getcustomers();
foreach (Models.Customer customer in list)
{
this._customer.Add(customer);
}
}
}
I widok (nie kod związany w tej chwili):
<UserControl x:Class="Customers.Customer"
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"
mc:Ignorable="d"
xmlns:vm ="clr-namespace:Customers.ViewModels"
d:DesignHeight="300" d:DesignWidth="300"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit" >
<Grid>
<toolkit:DataGrid ItemsSource="{Binding AllCustomers}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" AutoGenerateColumns="True">
</toolkit:DataGrid>
<toolkit:DataGrid ItemsSource="{Binding SelectedItem.Orders}">
</toolkit:DataGrid>
</Grid>
</UserControl>
I dataaccesslayer klasa:
class DataAccessLayer
{
public List<Customer> customers = new List<Customer>();
public static List<Customer> getcustomers()
{
entities db = new entities();
var customers = from c in db.Customer.Include("Orders")
select c;
return customers.ToList();
}
}
Problemem jest to, że brak danych jest wyświetlany po prostu dlatego, że kontekst danych nie jest ustawiony. Próbowałem to zrobić w kodzie z tyłu, ale nie działa. W każdym razie wolałbym to zrobić w pliku xaml. Innym problemem jest powiązanie SelectedItem - kod nigdy nie jest używany.
W swoim kodzie masz właściwość AllCustomers w swoim modelu widoku, ale wiążą Cię klienci. – mak
Czyściłem kod nieco i zrobiłem literówkę. Wiązanie w działającym kodzie jest oczywiście poprawne. – EVA