Datagrid不从ObservableCollection在MVVM中显示数据

时间:2015-03-17 21:21:39

标签: c# wpf mvvm datagrid observablecollection

我正在使用MVVM构建基本的WPF应用程序。我试图获取有关在Datagrid上显示的不同发电厂的数据。程序构建正常并显示网格线,但没有数据。我已经看过很多类似的问题,并尝试了几件事,但似乎没有任何效果。我想知道问题是否只是一件我不知道要找的问题。

查看:

public class Plant : INotifyPropertyChanged
{
    #region Properties

    private int plantID;
    public int PlantID
    {
        get { return plantID; }
        set
        {
            plantID = value;
            RaisePropertyChanged("PlantID");
        }
    }

    //...etc for all properties//
    #endregion

    void RaisePropertyChanged(string prop)
    {
        if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

视图模型:

public class MainViewModel : ViewModelBase, IPlantViewModel
{
    private ObservableCollection<Plant> _plants = new ObservableCollection<Plant>();
    private ICommand _loadCommand;

    public MainViewModel()
    {
        _plants = GetPlants();
        _plants.Add(new Plant (){PlantID=1, Name="Orange Plant", Address="1111 Orange Road", PlantPhone="(314)456 7489",PlantFax="(593)202 6948", Contact="John Smith"});
        _plants.Add(new Plant() { PlantID = 2, Name = "Blue Plant", Address = "2222 Blue Lane", PlantPhone = "6368967483", PlantFax = "783279948", Contact = "Jane Doe" });
    }

    public ObservableCollection<Plant> Plants
    {
        get { return _plants; }
    }

    public ObservableCollection<Plant> GetPlants()
    {
        if (_plants == null || _plants.Count == 0)
            _loadCommand.Execute(_plants);

        return _plants;
    }
}

查看:

    <UserControl 
    x:Class="Directory.MVVM.View.DirectoryView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit"
    xmlns:local="clr-namespace:Directory.ViewModel"
    Height="481" Width="708">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="21*"/>
        <ColumnDefinition Width="79*"/>
    </Grid.ColumnDefinitions>
    <DataGrid
        ItemsSource="{Binding Source=Plants}"
        Name="PlantGrid"
        HorizontalAlignment="Left" 
        Margin="82,54,0,0" 
        VerticalAlignment="Top" 
        Height="147" Width="515"
        AutoGenerateColumns="False" Grid.ColumnSpan="2">
        <DataGrid.DataContext>
            <local:MainViewModel />
        </DataGrid.DataContext>
        <DataGrid.Columns>
            <DataGridTextColumn Header="Plant ID" Width="89" Binding="{Binding Path=PlantID,UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
            <DataGridTextColumn Header="Name" Width="140" Binding="{Binding Path=Name,UpdateSourceTrigger=PropertyChanged, Mode=TwoWay }" />
            <DataGridTextColumn Header="Address" Width="90"    Binding="{Binding Path=Address, UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" />
            <DataGridTextColumn Header="Phone" Width="90" Binding="{Binding Path=PlantPhone, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
            <DataGridTextColumn Header="Fax" Width="60" Binding="{Binding Path=PlantFax,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" />
            <DataGridCheckBoxColumn Header="Contact" Width="58" Binding="{Binding Path=Contact, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
        </DataGrid.Columns>
    </DataGrid>

视图后面的代码(不确定我是否应该有更多内容):

public partial class DirectoryView : UserControl

public DirectoryView()
{
    InitializeComponent();

}

另外,我将此作为参考:

http://wpfgrid.blogspot.com/2014/02/simple-observablecollection-wpf-mvvm.html

3 个答案:

答案 0 :(得分:2)

尝试更改数据网格中的itemource绑定,而不是路径。从

ItemsSource="{Binding Source=Plants}"

ItemsSource="{Binding Path=Plants}"

ItemsSource="{Binding Plants}"

更改绑定将解决数据未在网格中显示的问题,至少对于您在mainviewmodel的构造函数中添加id为1和2的两个工厂。您还可以在构造函数中调用GetPlants,通过调用命令上的execute来加载其他工厂。我们无法看到您如何将植物添加到可观察的收集中。您可能想要了解如何将这些植物添加到getplants中的observablecollection中。如果评论出来

_plants = GetPlants();

in

  

MainViewModel

使您看到两个工厂在命令执行方法中添加项目时也存在问题。

答案 1 :(得分:1)

如果像你一样设置DataContext,每次UserControl加载新的时,你的datagrid都会获得MainViewmodel的新实例。

    <DataGrid.DataContext>
        <local:MainViewModel />
    </DataGrid.DataContext>

因此您必须先将itemssource更改为

ItemsSource="{Binding Path=Plants}"

现在你需要检查的是你如何填写&#34;你的收藏。如果您不使用添加,清除和删除来更改您的集合,那么您必须提高OnPropertyChanged(),以便WPF注意到有更改。

public ObservableCollection<Plant> Plants
{
    get 
    {
        return _plants;
    }

    set 
    {
         _plants = value;
         OnPropertyChanged();
    }

}

答案 2 :(得分:0)

以下是我的表现方式:

Window Constructor实例化视图模型(这里我将它作为属性但实例化也可以在构造函数内)并将DataContext设置为ViewModel:

public partial class WinFilesTransmitted : Window
{
    static FTViewModel w = new FTViewModel();
    public WinFilesTransmitted()
    {
        InitializeComponent();
        DataContext = w;
    }
}

DataGrid xaml然后执行此操作:

<DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch"
                        ItemsSource="{Binding DataContext.oFTrn, RelativeSource={RelativeSource AncestorType={x:Type Window}}}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding UID}" Header="xID" Width="40"/>
        <DataGridTextColumn Binding="{Binding TransID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="TransID" Width="40"/>
        <DataGridTextColumn Binding="{Binding DocID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="DocID" Width="40"/>
        <DataGridTextColumn Binding="{Binding TransmittalName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="325">

因此datagrid的ItemsSource设置为我的observablecollection,并且列直接绑定到属性。