WPF显示来自Observable Collection MVVM的对象属性

时间:2014-08-30 22:05:26

标签: wpf mvvm data-binding observablecollection

我正在尝试显示包含在可观察列表中的对象的属性,但它只是不起作用。 我希望有人能指出我正确的方向。

这是我的XAMl

<Window x:Name="MainViewWindow" x:Class="WpfApplication1.View.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local ="clr-namespace:WpfApplication1.ViewModel"
    Title="MainView" Height="413.514" Width="607.095">
<Window.DataContext>
    <local:MainViewModel />
</Window.DataContext>
<Grid>
    <Label Content="Text:" HorizontalAlignment="Left" Margin="55,135,0,0" VerticalAlignment="Top"/>
    <Label Content="{Binding Name}" HorizontalAlignment="Left" Margin="98,135,0,0" VerticalAlignment="Top"/>
    <Button Content="Button" HorizontalAlignment="Left" Margin="61,108,0,0" VerticalAlignment="Top" Width="75" Command="{Binding UpdateNameCommand}"/>
    <Label Content="ActivateButton" HorizontalAlignment="Left" Margin="52,82,0,0" VerticalAlignment="Top"/>
    <CheckBox Content="CheckBox" HorizontalAlignment="Left" Margin="173,87,0,0" VerticalAlignment="Top" IsChecked="{Binding ButtonActive}" />
    <Label Content="CustomerName" HorizontalAlignment="Left" Margin="55,166,0,0" VerticalAlignment="Top"/>
    <StackPanel HorizontalAlignment="Left" Height="100" Margin="173,166,0,0" VerticalAlignment="Top" Width="100"/>
    <ItemsControl x:Name="lstPeople" Background="AliceBlue" Width="130" Margin="273,29,196,35" ItemsSource="{Binding CustomerList}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

我的CustomerList是位于MainViewModel中的属性:

     ObservableCollection<Customer> _CustomerList;
  ObservableCollection<Customer> CustomerList
  {
      get { return _CustomerList; }
      set
      {
          if (_CustomerList != value)
          {
              _CustomerList = value;
              PropertyChanged(this, new PropertyChangedEventArgs("CustomerList"));

          }
      }
  }

我的Customer类只包含一个属性:Name

  public class Customer : INotifyPropertyChanged
{
    private string _Name;
    public string Name
    {
        get { return _Name; }
        set
        {
            if (_Name != value)
            {
                _Name = value;
                PropertyChanged(this, new PropertyChangedEventArgs("Name"));
            }
        }
    }


    public event PropertyChangedEventHandler PropertyChanged = delegate { };
}

我在MainViewModel构造函数中创建了一个CustomerList实例,但我看不到任何客户出现在应用程序中:

 public MainViewModel()
  {
      ButtonActive = true;
      CustomerList = new ObservableCollection<Customer>() { new Customer() { Name = "NewCust33" } };
      CustomerList.Add(new Customer() { Name = "NewCust" });

  }

1 个答案:

答案 0 :(得分:1)

看起来你绑定的属性是私有的吗?

您只能绑定到public properties

public ObservableCollection<Customer> CustomerList