XAML绑定属性未按预期工作

时间:2016-08-23 21:13:43

标签: c# xaml binding

我有一个Crew属性,该属性有几个字段,其中很少是Code和InvoiceAmount。加号按钮应该将新的工作人员插入到ObservableCollection的工作人员中。添加第一个项目工作正常,但是当插入第二个项目时,第一个项目的代码更改为第二个项目,第二个项目没有可见代码。如何修复它以便每次单击+按钮时插入新的工作人员?

启动用户界面:

enter image description here

添加一个项目(a)后:

enter image description here

已添加第二项(b):

enter image description here

这是ViewModel代码:

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;
}

1 个答案:

答案 0 :(得分:1)

这是因为您没有为PropertyChanged属性举起Crew事件,因此文本框仍然绑定到之前添加的工作人员。

将您的MainPageViewModel.Crew媒体资源更改为以下内容:

public class MainPageViewModel : ViewModelBase
{
    .............
    private Crew _crew = new Crew();
    public Crew Crew
    {
        get { return _crew; }
        set
        {
            if (_crew == value) return;
            _crew = value;
            RaisePropertyChanged(nameof(Crew));
        }
    }
    .......
}