1
我有一個命令的視圖模型。但是隻有最後添加的項目可以通過命令進行編輯。當你看頌歌時,這很有意義。但這不是我想要的。我想要選擇的項目進行編輯。我就勾勒我的問題:MVVM命令選擇最後添加的項目
我有一個模型,名爲部分
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>
最後添加的項目(零件)被編輯。這是有道理的,因爲在視圖模型下面的代碼:
_part = item;
如何將命令綁定到選定的項目。我猜想視頻模型一定有問題,而不是綁定。每次添加新零件時都會覆蓋_part get。但是,我怎麼能改變這個,所以它會工作?
我得到你要去的地方,但現在我得到一個NullReferenceException。 UpdateDescriptionExecure中的'part'參數爲null,表示它不傳遞選定的部分。有任何想法嗎? – Marcel
您是否從XAML標記中的
謝謝!忽略了那一個。還有一個問題,但會爲這個問題提出一個新的話題.. – Marcel