我有一个列表,可以从可观察的集合ComputerList
加载项目 <ListView x:Name="icTodoList" ItemsSource="{Binding ComputerList}" SelectedItem="{Binding SelectedComputer}" Grid.Column="3" SelectionChanged="icTodoList_SelectionChanged_1">
<ListView.ItemTemplate>
<DataTemplate>
<Border BorderBrush="{Binding borderColor }" BorderThickness="2" Margin="0,0,0,1">
<Grid Margin="2" Height="auto" Width="auto">
<Button Height="18" Command="{Binding RemoveComputer}" HorizontalAlignment="Right" ToolTipService.ShowDuration="60000" Margin="0,1,38,0" x:Name="button1_Copy" VerticalAlignment="Top" Width="25" FontSize="11" Foreground="#FF6BADF6" Content="" BorderBrush="#FF6BADF6" Grid.Column="8"/>
</Grid>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我的按钮点击应该从observableCollection中删除项目,所以我用这种方式构建了Icommand接口(简称版本)。
class ComputerViewModel : ViewModelBase
{
CustomClass _customClass = new CustomClass();
public readonly ObservableCollection<Model.Model.ControleData> _ComputerList = new ObservableCollection<Model.Model.ControleData>();
public ObservableCollection<Model.Model.ControleData> ComputerList { get { return _ComputerList; } }
public ComputerViewModel()
{
ComputerList.Add(new Model.Model.ControleData { ComputerName = "TESTMACHINE", titlePing = "online",borderColor = Genkai.BlueMain });
// TextBoxText = "init";
_canExecute = true;
}
private ICommand _RemoveComputer;
public ICommand RemoveComputer
{
get
{
return _RemoveComputer ?? (_RemoveComputer = new CommandHandler(() => RemoveComp(), _canExecute));
}
}
private bool _canExecute;
public void RemoveComp()
{
Debug.WriteLine("close Item");
}
public class CommandHandler : ICommand
{
private Action _action;
private bool _canExecute;
public CommandHandler(Action action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}
public void Execute(object parameter)
{
_action();
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged;
}
}
单击时不会触发动作removecomp。
但是在我的视图模型中,它被解雇了
var hwc = new CommandHandler(RemoveComp,true);
if (hwc.CanExecute(this))
hwc.Execute(this);
所以我想我错过了WPF视图中的内容。
答案 0 :(得分:0)
您正尝试在datatemplate中绑定VM命令。它无法找到此命令,因为它具有不同的上下文。 尝试以这种方式绑定
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type controls:TypeOfYourControlOrWindow}}, Path=DataContext.YourCommand}"