无法编辑DataGrid中的项目

时间:2013-05-17 07:11:37

标签: c# wpf wpfdatagrid mvvm-light

我已经在我的主视图中添加了一个DataGrid,但现在我遇到了问题,我无法编辑值,也没有添加新行。删除行虽然有效,但有人可以告诉我这里我做错了吗?

编辑:正在使用MVVM Light Toolkit

创建此项目

MainWindow.xaml

<Window x:Class="PartExplorer.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:ignore="http://www.ignore.com"
    mc:Ignorable="d ignore"
    Height="300"
    Width="300"
    Title="{Binding WelcomeTitle}"
    DataContext="{Binding Main, Source={StaticResource Locator}}">

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Skins/MainSkin.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

    <Grid x:Name="LayoutRoot">
        <DataGrid ItemsSource="{Binding PriceItems, Mode=TwoWay}" IsReadOnly="False" CanUserAddRows="True"  />
    </Grid>
</Window>

MainViewModel.cs

...
    /// <summary>
    /// The <see cref="PriceItems" /> property's name.
    /// </summary>
    public const string PriceItemsPropertyName = "PriceItems";

    private ObservableCollection<PriceItem> _priceItems = new ObservableCollection<PriceItem>();

    /// <summary>
    /// Sets and gets the PriceBook property.
    /// Changes to that property's value raise the PropertyChanged event. 
    /// </summary>
    public ObservableCollection<PriceItem> PriceItems
    {
        get
        {
            return _priceItems;
        }

        set
        {
            if (_priceItems == value)
            {
                return;
            }

            RaisePropertyChanging(PriceItemsPropertyName);
            _priceItems = value;
            RaisePropertyChanged(PriceItemsPropertyName);
        }
    }
...

PriceItem.cs

public class PriceItem
{
    public PriceItem()
    {
        Name = "";
        Price = 0;
        Weight = 0;
        PartType = Type.Standard;
    }

    public PriceItem(string name, double price, int weight, Type partType)
    {
        Name = name;
        Price = price;
        Weight = weight;
        PartType = partType;
    }

    public Type PartType { get; private set; }
    public string Name { get; private set; }
    public double Price { get; private set; }
    public int Weight { get; private set; }
}

public enum Type
{
    Standard,
    Special
}

1 个答案:

答案 0 :(得分:2)

好的,我很蠢。 将PriceItem课程中的制定者设为公开。