Pergunta

Estou tentando ligar meu ponto de vista para o meu modelo de visão sem DataObjectProvider.

O seguinte código é executado sem um erro , mas o meu ListBox é esvaziar .

Tanto quanto eu posso dizer, eu corretamente:

  • set do Ver DataContext para o próprio (DataContext = new CustomersViewModel();) ViewModel
  • expor os objetos de clientes no ViewModel (public static ObservableCollection<Customer> GetAll())
  • ligar o ListBox aos objetos de clientes (ItemsSource="{Binding GetAll}")

O pequeno pedaço de sintaxe estou em falta aqui?

CustomersView.xaml:

<UserControl x:Class="TestDynamicForm123.View.CustomersView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <UserControl.Resources>
        <Style x:Key="allCustomersListBox" TargetType="ListBox">
            <Setter Property="BorderThickness" Value="0"/>
        </Style>
        <DataTemplate x:Key="allCustomersDataTemplate">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding FirstName}"/>
                <TextBlock Text=" "/>
                <TextBlock Text="{Binding LastName}"/>
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>

    <StackPanel Style="{StaticResource viewWrappingStackPanel}">
        <ListBox ItemsSource="{Binding GetAll}"
                 ItemTemplate="{StaticResource allCustomersDataTemplate}"
                 Style="{StaticResource allCustomersListBox}">
        </ListBox>
    </StackPanel>
</UserControl>

CustomersView.xaml.cs:

using System.Windows.Controls;
using TestDynamicForm123.ViewModel;

namespace TestDynamicForm123.View
{
    public partial class CustomersView : UserControl
    {
        public CustomersView()
        {
            InitializeComponent();

            DataContext = new CustomersViewModel();
        }
    }
}

CustomersViewModel.cs:

using System.Collections.ObjectModel;

namespace TestDynamicForm123.ViewModel
{
    public class CustomersViewModel
    {
        public static ObservableCollection<Customer> GetAll()
        {
            return Customer.GetAll();
        }
    }
}

Customer.cs: (modelo)

using System.Collections.ObjectModel;

namespace TestDynamicForm123.ViewModel
{
    public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public static ObservableCollection<Customer> GetAll()
        {
            ObservableCollection<Customer> customers = new ObservableCollection<Customer>();
            customers.Add(new Customer() { FirstName = "Jay", LastName = "Anders", Age = 34 });
            customers.Add(new Customer() { FirstName = "Jim", LastName = "Smith", Age = 23 });
            customers.Add(new Customer() { FirstName = "John", LastName = "Jones", Age = 22 });
            customers.Add(new Customer() { FirstName = "Sue", LastName = "Anders", Age = 21 });
            customers.Add(new Customer() { FirstName = "Chet", LastName = "Rogers", Age = 35 });
            customers.Add(new Customer() { FirstName = "James", LastName = "Anders", Age = 37 });
            return customers;
        }

    }
}
Foi útil?

Solução

O problema é que você está tentando se ligam a CustomerViewModel.GetAll (), quando GetAll em CustomerViewModel é uma função estática não uma propriedade de instância.

Alterar a função estática para algo como isto (em CustomerViewModel):

public ObservableCollection<Customer> GetAll
{
    get { return Customer.GetAll(); }
}

Outras dicas

O problema é que CustomersViewModel .GetAll() é um método estático. Encadernação só funciona com propriedades de instância. Você deve mover a implementação de GetAll() para o construtor, e depois expor a coleção como uma propriedade de instância da classe.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top