0
我有一個Crew屬性,該屬性有幾個字段,其中很少是Code和InvoiceAmount。加號按鈕應該是將一個新的船員插入到船員的ObservableCollection中。添加第一個項目可以正常工作,但是當插入第二個項目時,第一個項目的代碼會更改爲第二個項目,而第二個項目不會顯示可見的代碼。我該如何解決這個問題,以便每次點擊+按鈕時都會插入新的工作人員?XAML綁定屬性不按預期工作
啓動UI:
(a)之後被添加一個項目:
第二項(b)已被添加:
這裏的視圖模型代碼:
public class MainPageViewModel : ViewModelBase
{
public MainPageViewModel()
{
AddCrewCommand = new CustomCommand(param => addCrew(), null);
Crews.CollectionChanged += new NotifyCollectionChangedEventHandler(Crews_Updated);
}
private void Crews_Updated(object sender, NotifyCollectionChangedEventArgs e)
{
RaisePropertyChanged("lvCrewList");
}
public Crew Crew { get; set; } = new Crew();
public ObservableCollection<Crew> Crews { get; private set; } = new ObservableCollection<Crew>();
public Crew SelectedCrew { get; set; }
public ICommand AddCrewCommand { get; private set; }
private void addCrew()
{
Crews.Add(Crew);
Crew = new Crew();
}
public ObservableCollection<string> SelectedWorkOrder { get; set; }
}
ViewModelBase:
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
下面是分配的代碼字段的XAML位:
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" >
<Label Content="Crew" Width="55" Height="25" Margin="10,10,0,0"/>
<TextBox x:Name="txtCrew" Width="75" Height="25" Margin="0,10,10,0"
Text="{Binding Crew.Code, Mode=TwoWay}" />
<Button Content="+" Width="25" Height="25" Margin="0, 10, 0, 0" Command="{Binding AddCrewCommand}" />
</StackPanel>
船員類別:
public class Crew
{
public string Code { get; set; }
public decimal InvoiceAmount { get; set; } = 0;
public Job Job { get; set; }
public override string ToString() => Code;
}
我們可以看到網格綁定? –