【问题标题】:MVVM Command selects the last added itemMVVM 命令选择最后添加的项目
【发布时间】:2017-06-10 17:38:19
【问题描述】:

我有一个带有命令的视图模型。但只有最后添加的项目可以通过该命令进行编辑。当你看颂歌时,这是有道理的。但这不是我想要的。我希望编辑所选项目。我将勾勒出我的问题:

我有一个模型,名为 Part

 public class Part
 {
    private string _partcode;
    private string _description;

    public string PartCode
    {
        get { return _partcode.Trim(); }
        set { _partcode = value; }
    }

    public string Description
    {
        get { return _description; }
        set { _description = value; }
    }
  }

带有命令的 ViewModel,名为 PartViewModel

    /// <summary>
    /// Returns a ViewModel containing all parts.
    /// </summary>
    /// <param name="dt">Database to use.</param>
    public PartViewModel(DatabaseType dt)
    {
        GenerateViewModelForAllParts(dt);
    }
    private async void GenerateViewModelForAllParts(DatabaseType dt)
    {
        using (NexusWCFServiceClient client = new NexusWCFServiceClient())
            foreach (Part item in await client.GetAllPartsAsync(dt))
            {
                _part = item;
                _items.Add(item);
            }
    }
    #endregion

    #region Members
    private ObservableCollection<Part> _items = new ObservableCollection<Part>();

    private Part _part;
    int count = 0;
    #endregion

    #region Properties
    public ObservableCollection<Part> Items
    {
        get { return _items; }
        set { _items = value; }
    }

    public Part Part
    {
        get { return _part; }
        set { _part = value; }
    }

    public string PartCode
    {
        get { return Part.PartCode; }
        set
        {
            if (Part.PartCode != value) /* Check if value is changed */
            {
                Part.PartCode = value;
                RaisePropertyChanged("PartCode");  /* Raise event */
            }
        }
    }

    public string Description
    {
        get { return Part.Description; }
        set
        {
            if (Part.Description != value)
            {
                Part.Description = value;
                RaisePropertyChanged("Description");
            }
        }
    }

    #region Commands
    private void UpdateDescriptionExecute()
    {
        //count++;
        //Description = Description + count.ToString();
        // Part.Description = "asdasdasd";
        MessageBox.Show(PartCode);
    }

    private bool CanUpdateDescriptionExecute()
    {
        if (count >= 2)
            return false;
        else
            return true;
    }

    public ICommand UpdateDescription
    {
        get
        {
            return new RelayCommand(UpdateDescriptionExecute, CanUpdateDescriptionExecute);
        }
    }
    #endregion
}

现在每当我尝试在视图中触发命令时:

<Window x:Class="NexusWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="700" Width="525" x:Name="TestView">
    <Grid>
        <StackPanel x:Name="stck">
            <ListView x:Name="lb" ItemsSource="{Binding Items}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Vertical" x:Name="stck">
                            <TextBlock Text="{Binding Path=PartCode}"/>
                            <TextBlock Text="{Binding Path=Description}"/>
                            <Button Content="Update" DataContext="{Binding ElementName=TestView, Path=DataContext}" Command="{Binding UpdateDescription}" CommandParameter="{Binding}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackPanel>
    </Grid>
</Window>

最后添加的项目(部分)被编辑。这是有道理的,因为 ViewModel 中有以下代码:

 _part = item;

如何将命令绑定到所选项目。我想 viewmodel 一定有问题,而不是绑定。 _part get 每次添加新部件时都会被覆盖。但是我怎样才能改变它,让它起作用呢?

【问题讨论】:

    标签: c# wpf mvvm command


    【解决方案1】:

    使用接受Part 命令参数的RelayCommand&lt;Part&gt;

    public ICommand UpdateDescription
    {
        get
        {
            return new RelayCommand<Part>(UpdateDescriptionExecute, CanUpdateDescriptionExecute);
        }
    }
    
    private void UpdateDescriptionExecute(Part part)
    {
        MessageBox.Show(part.PartCode);
    }
    
    private bool CanUpdateDescriptionExecute(Part part)
    {
        if (count >= 2)
            return false;
        else
            return true;
    }
    

    并且稍微修改一下Command绑定:

    <Button Content="Update" Command="{Binding DataContext.UpdateDescription,ElementName=TestView}" CommandParameter="{Binding}"/>
    

    【讨论】:

    • 我知道你要去哪里,但现在我得到一个 NullReferenceException。 UpdateDescriptionExecure 中的 'part' 参数为 null,表示它没有传递选定的部分。有什么想法吗?
    • 您是否从 XAML 标记中的
    • 谢谢!忽略了那个。还有一个问题,但会为那个问题提出一个新话题..
    猜你喜欢
    • 2016-07-19
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    相关资源
    最近更新 更多