WPF绑定ViewModel

时间:2019-05-27 08:36:18

标签: c# wpf mvvm

因此,我目前正在尝试通过MVVM学习WPF,并且正在在线关注一些教程。现在,我有一个简单的项目,我尝试独自完成此操作,但ListBox仍然保持空白。我认为,它并不局限于视图模型。我在这里想念什么?任何帮助表示赞赏。

型号:

public class Person : INotifyPropertyChanged
{
    private string _vorname;
    private string _nachname;
    private string _email;

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string property) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));

    public string Vorname
    {
        get { return _vorname; }
        set
        {
            _vorname = value;
            RaisePropertyChanged(nameof(Vorname));
        }
    }

    public string Nachname
    {
        get { return _nachname; }
        set
        {
            _nachname = value;
            RaisePropertyChanged(nameof(Nachname));
        }
    }

    public string Email
    {
        get { return _email; }
        set
        {
            _email = value;
            RaisePropertyChanged(nameof(Email));
        }
    }

}

查看:

<UserControl.Resources>
    <DataTemplate x:Key="personenTemplate">
        <StackPanel Orientation="Horizontal">
            <TextBox Width="200" Margin="3,5,3,5"
                     Text="{Binding Path=Vorname, Mode=TwoWay}" />
            <TextBox Width="200" Margin="0,5,3,5"
                     Text="{Binding Path=Nachname, Mode=TwoWay}" />
            <TextBox Width="200" Margin="0,5,3,5"
                     Text="{Binding Path=Email, Mode=TwoWay}" />
        </StackPanel>
    </DataTemplate>
</UserControl.Resources>

<Grid>
    <StackPanel Orientation="Horizontal">
        <ListBox Width="500"
                 ItemTemplate="{StaticResource personenTemplate}"
                 ItemsSource="{Binding Personen}" />
    </StackPanel>
</Grid>

ViewModel:

public class PersonViewModel
{
    ObservableCollection<Person> Personen { get; set; } = new ObservableCollection<Person>();

    public PersonViewModel()
    {
        Personen.Add(new Person { Vorname = "My", Nachname = "Name", Email = "my@name.com" });
        Personen.Add(new Person { Vorname = "Max", Nachname = "Mustermann", Email = "max@mustermann.de" });
        Personen.Add(new Person { Vorname = "John", Nachname = "Doe", Email = "john@doe.com" });
        Personen.Add(new Person { Vorname = "Jane", Nachname = "Doe", Email = "jane@doe.com" });
    }
}

}

此外,我还在[..] View.xaml.cs

上设置了DataContext
public PersonenView()
{
    InitializeComponent();
    this.DataContext = new ViewModel.PersonViewModel();
}

1 个答案:

答案 0 :(得分:4)

您只需要在ViewModel中为ObservableCollection Personen提供公共访问器即可。

您还应该将属性设置为只读(或从设置程序中触发属性更改通知):

public ObservableCollection<Person> Personen { get; }
    = new ObservableCollection<Person>();