我是使用 RelayCommands 的新手(遵循 Josh Smith 的 MVVMDemoApp)并且可以使用一些帮助来识别我的错误。
我有两个列表框。当第一个中的一个项目被选中并按下“添加”按钮时,将执行 AddCommand 并且第二个列表的 ObservableCollection 将 selectedItem 添加到其中。
我的观点:
<DockPanel >
<Border DockPanel.Dock="Bottom" Height="50" HorizontalAlignment="Left" Width="150" >
<!--Notice here that the Button was disabled until it was given a DataContext, which allowed the CanAddPN to be true-->
<Button Command="{Binding Path=AddToPartsBinCommand}" Content="Add >" />
</Border>
<UniformGrid Columns="2" Rows="1" DockPanel.Dock="Top" >
<!--ListBox 1 (PartNumbersCollection)-->
<ListBox Background="PaleGoldenrod"
ItemsSource="{Binding PnsCollection, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding SelectedPartNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding pn}">
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!--ListBox 2 (SelectedPartNumbersCollection)-->
<ListBox ItemsSource="{Binding PartsBinCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding pn}">
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</UniformGrid>
</DockPanel>
我的视图模型:
//DummyDBEntities _context;
public ObservableCollection<PartNumber> _pnsCollection;
public ObservableCollection<PartNumber> _partsBinCollection;
PartNumber _selectedPN;
public ICommand _addToPartsBinCommand;
public MasterViewModel(DummyDBEntities _context)
{
_context = new DummyDBEntities();
this._pnsCollection = new ObservableCollection<PartNumber>(_context.PartNumbers);
this._partsBinCollection = new ObservableCollection<PartNumber>();
}
public ObservableCollection<PartNumber> PnsCollection
{
get { return this._pnsCollection; }
set
{
_pnsCollection = value;
OnPropertyChanged("PnsCollection");
}
}
public PartNumber SelectedPN
{
get { return this._selectedPN; }
set
{
this._selectedPN = value;
OnPropertyChanged("SelectedPN");
OnPropertyChanged("PartsBinCollection");
}
}
public ObservableCollection<PartNumber> PartsBinCollection
{
get
{
if (_partsBinCollection == null)
{
_partsBinCollection = new ObservableCollection<PartNumber>();
}
return this._partsBinCollection;
}
set
{
this._partsBinCollection = value;
OnPropertyChanged("PartsBinCollection");
}
}
public ICommand AddToPartsBinCommand
{
get
{
if (_addToPartsBinCommand == null)
_addToPartsBinCommand = new RelayCommand(() => this.AddPN(),
() => this.CanAddPN());
return this._addToPartsBinCommand;
}
}
private bool CanAddPN()
{
return true;
}
private void AddPN()
{
if (this._partsBinCollection == null)
{
this._partsBinCollection = new ObservableCollection<PartNumber>();
}
this._partsBinCollection.Add(this._selectedPN);
}
提前致谢!
另外:为什么会:
private bool CanAddPN()
{
return this._selectedPN != null;
}
让我的添加按钮永久禁用?我没有做什么让按钮知道一个项目已被选中?这似乎是我理解为什么命令永远不会触发的相同缺失的链接。
再次感谢!