【发布时间】:2016-06-20 14:42:35
【问题描述】:
我有一个从可观察集合 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 视图中错过了一些东西。
【问题讨论】:
-
是的,似乎同样的问题,但痛苦理解尝试 仍然没有触发
-
不建议将
CanExecute作为布尔值传递,而是作为Func<bool>传递,否则您以后无法轻松更改该值。您的命令类还需要提供一个可以调用的方法来引发CanExecuteChanged,当CanExecute函数的返回值可能发生变化时需要触发该方法。