- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个带有 ListBox
的窗口绑定(bind)到 List<MyThing>
的实例.类(class)MyThing
包含属性 Name
显示在 ListBox
中.
我还有一个 Button
,我想在单击时运行以下方法:
void RunMe(MyThing m) { ... }
作为此方法的参数,我想使用 SelectedItem
来自 ListBox
.
我该怎么做?
这是我的 MyWindow
的 XAML 文件类:
<Window x:Class="MyProject.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<ListBox x:Name="lb" ItemsSource="{Binding MyThingList}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Content="Run command!" Command="{Binding RunCommand}"/>
</StackPanel>
</Window>
DataContext
的 MyWindow
设置为 MyVM
的一个实例,定义如下。除 InitializeComponent
外,此 XAML 的代码隐藏为空.
这是我的 ViewModel 类 MyVM
:
public class MyVM
{
public IList<MyThing> MyThingList { get; private set; }
public MyVM(IList<MyThing> aThingList)
{
MyThingList = aThingList;
RunCommand = // somehow connect it to method "RunMe"
}
public void RunMe(MyThing m) { ... }
public ICommand RunCommand { get; private set; }
}
有经验的人可能会看到,我真的不知道自己在做什么。所以这里有一些具体的问题:
为什么我不能简单地将按钮绑定(bind)到每次单击时调用的任何方法?为什么一定要是命令,有什么好处? (我知道一个命令可以自动跟踪它的可执行性,当它不能执行时按钮变灰,但现在,我不关心这个。我也知道它可以绑定(bind)到一个事件,但似乎此事件必须在代码隐藏中定义,我想将其保留为空。如果我错了请纠正我。)
如何连接我的 RunMe
命令的方法 RunCommand
在 MyVM
的构造函数中? (我试过 RunCommand = new RoutedUICommand("RunMe", "RunMe", typeof(MyVm));
,但按钮是灰色的。我也试过 typeOf(MyWindow)
和 typeof(Window)
,但它仍然是灰色的。)
假设我让这个工作正常,点击按钮会导致调用方法 RunMe
.我如何递交 SelectedItem
来自 ListBox
到 RunMe
方法? (我知道我可以将按钮的 DataContext
更改为 DataContext="{Binding Path=SelectedItem, ElementName=lb}"
,但是这样可能找不到命令,我仍然不知道如何让按钮将这个选中的项目交给方法。)
我的方法是否存在根本性错误?我仍在努力掌握任何东西(一般的 GUI 编程、事件/命令、WPF、MVVM 模式——同时对我来说都是新的),所以如果你有更好的方法,请告诉我。
PS:请随意将标题更改为更具表现力的内容。我有很多问题,很难将其归结为一个...
最佳答案
ICommand
远比简单的方法调用灵活和强大。如果你确实想要一个简单的方法调用(好吧,有点简单......大概),你可以只处理 Button 的 Click
。事件:
protected void RunCommandButton_Click(object sender, RoutedEventArgs args)
{
var vm = (MyVM)DataContext;
var selectedThing = lb.SelectedItem as MyThing;
if (selectedThing != null)
{
vm.RunMe(selectedThing);
}
}
这不是“正确的方法”,但有时它已经足够好了。我们并不总是需要 build 帕特农神庙。有时我们只需要一 block 防水布来挡住木柴上的雨水。
如果你正在使用命令(你应该学会使用命令),你应该使用 DelegateCommand
执行您的命令。 WPF 应该立即包含这样的东西,但不幸的是他们没有。他们提供的内容让您自己弄清楚是非常痛苦的。 MS Prism has one ,虽然我没用过。下面我包含了一个非常简单的非通用版本。
private DelegateCommand _runCommand;
public ICommand RunCommand {
get {
if (_runCommand == null)
{
_runCommand = new DelegateCommand(RunCommandExecute, ExecuteCanExecute);
}
return _runCommand;
}
}
protected void RunCommandExecute(Object parameter)
{
// Do stuff
}
protected bool RunCommandCanExecute(Object parameter)
{
// Return true if command can be executed
return parameter != null;
}
像这样绑定(bind):
<Button
Content="Run command!"
Command="{Binding RunCommand}"
CommandParameter="{Binding SelectedItem, ElementName=lb}"
/>
此外,使用 ObservableCollection<T>
对于您的列表项而不是 List<T>
.这样,当您添加和删除列表项时,列表框将自动更新。
DelegateCommand.cs
using System;
using System.Windows.Input;
namespace HollowEarth.MVVM
{
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event EventHandler CanExecuteChanged;
#region Constructors
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action execute)
: this(o => execute(), null)
{
}
public DelegateCommand(Action execute, Func<bool> canExecute)
{
_execute = o => execute();
_canExecute = o => canExecute();
}
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
#endregion Constructors
public virtual bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public virtual void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
}
关于c# - 基本理解: binding methods with arguments to controls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39750141/
例如,如果我的程序名称是 test.c 然后对于以下运行命令,argc = 2 而不是 4。 $test abc pqr* *xyz* 最佳答案 尝试运行: $ echo abc pqr* *xyz*
我正在尝试使用一个容器来显示TextField,但是该容器不喜欢我的操作顺序。这是我的代码: Widget build(BuildContext context) { return Scaffol
我有以下代码: class MetricGoogleGateway extends AMetricGateway{ constructor(id, name, token) {
我像这样调用下面的对象方法。 new Cout( elem1 ).load( 'body' ) new COut( elem1 ).display( 'email' ) 我一次只使用一个实例。因为我一
我正在尝试使用 C++11 中的可变参数函数模板,并通过如下代码了解了基本思想: void helper() { std::cout void helper( T&& arg ) {
在学习 ExtJS 4 时,我发现在定义一个新类时,在 initComponent 中方法可以使用 this.callParent(arguments) 调用父类的构造函数. 我想知道这个 argum
使用 XCode 9,Beta 3。Swift 4。 statsView.createButton("Button name") { [weak self] Void in //stuff st
以下代码将打印1: (function (arguments) { console.log(arguments); }(1, 2)); 实际上,arguments 对象已被覆盖。是否可以恢复函
/** * @param $name * @return Response * @Route ("/afficheN/{name}",name="afficheN") */ public fu
我习惯使用Scala scopt用于命令行选项解析。您可以选择参数是否为 .required()通过调用刚刚显示的函数。 如何定义仅在定义了另一个参数时才需要的参数? 例如,我有一个标志 --writ
所以这是我的代码: def is_valid_move(board, column): '''Returns True if and only if there is an o
我试图在这里运行此代码: threads = [threading.Thread(name='ThreadNumber{}'.format(n),target=SB, args(shoe_type,m
在静态类型函数编程语言(例如 Standard ML、F#、OCaml 和 Haskell)中,编写函数时通常将参数彼此分开,并通过空格与函数名称分开: let add a b = a + b
function validateArguments(args) { if(args.length 2) { throw new RangeError("Invalid amo
我正在使用 Django 1.5 并尝试将参数传递到我的 URL。当我使用前两个参数时,下面的代码工作正常,使用第三个参数时我收到错误。我已经引用了新的 Django 1.5 更新中的 url 用法,
我刚刚开始使用 ember js 并且多次被这个功能绊倒 有人可以简要介绍一下 this._super() 的使用,并解释 ...arguments 的重要性 谢谢 最佳答案 每当您覆盖类/函数(例如
这个问题在这里已经有了答案: How to fix an "Argument passed to call that takes no arguments" error? (2 个答案) 关闭 3
我正在创建一个简单的登录注册应用程序。但是我遇到了错误,我不知道如何解决,请帮忙!这是我的代码: // // ViewController.swift // CHLogbook-Applicati
我是 Swift 的初学者。我尝试创建一个表示 Meal 的简单类。 它有一些属性和一个返回可选的构造函数 但是当我尝试测试它或在任何地方实例化它时,我得到的只是一个错误。似乎无法弄清楚发生了什么。
我有一个在特殊环境下运行其他程序的系统程序: cset shield -e PROGRAM .现在要运行一个 java 程序,我输入了 cset shield -e java PROGRAM ,但这不
我是一名优秀的程序员,十分优秀!