13

私のビューには、ボタンがあります。

ユーザーがこのボタンをクリックすると、ViewModel が TextBlock のコンテキストをデータベースに保存するようにします。

<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
    <TextBlock Text="{Binding FirstName}"/>
    <TextBox Text="Save this text to the database."/>
    <Button Content="Save" Command="{Binding SaveCommand}"/>
</StackPanel>

ただし、ViewModel の DelegateCommand では、「Save()」メソッドは引数を渡さないため、その時点でビューからデータを取得するにはどうすればよいでしょうか?

#region DelegateCommand: Save
private DelegateCommand saveCommand;

public ICommand SaveCommand
{
    get
    {
        if (saveCommand == null)
        {
            saveCommand = new DelegateCommand(Save, CanSave);
        }
        return saveCommand;
    }
}

private void Save()
{
    TextBox textBox = ......how do I get the value of the view's textbox from here?....
}

private bool CanSave()
{
    return true;
}
#endregion
4

5 に答える 5

20

Josh Smith によるこの MSDN の記事を参照してください。その中で、彼は RelayCommand を呼び出す DelegateCommand のバリエーションを示し、RelayCommand の Execute デリゲートと CanExecute デリゲートはオブジェクト型の 1 つのパラメーターを受け入れます。

RelayCommand を使用すると、CommandParameter を介してデリゲートに情報を渡すことができます。

<Button Command="{Binding SaveCommand}" 
        CommandParameter="{Binding SelectedItem,Element=listBox1}" />

アップデート

この記事を見ると、同様の方法でパラメーターを受け入れる DelegateCommand の汎用バージョンがあるようです。SaveCommand を aDelegateCommand<MyObject>に変更し、Save メソッドと CanSave メソッドを変更して、MyObject パラメーターを受け取るようにしてください。

于 2009-05-28T10:28:15.433 に答える
13

これがエレガントな方法です。

テキストボックスに名前を付けてから、ボタンの CommandParameter をその Text プロパティにバインドします。

<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
    <TextBlock Text="{Binding FirstName}"/>
    <TextBox x:Name="ParameterText" Text="Save this text to the database."/>
    <Button Content="Save" Command="{Binding SaveCommand}"
            CommandParameter="{Binding Text, ElementName=ParameterText}"/>
</StackPanel>
于 2009-09-03T15:13:46.833 に答える
12

VM で:

private DelegateCommand<string> _saveCmd = new DelegateCommand<string>(Save);

public ICommand SaveCmd{ get{ return _saveCmd } }

public void Save(string s) {...}

View では、Matt の例のように CommandParameter を使用します。

于 2009-05-28T17:41:14.170 に答える
5

ボタンコマンドを介してデータを渡すことについて質問しています。

実際に必要なのは、Textbox のテキストをViewModelのパブリック プロパティにバインドすることだと思います。

<!-- View: TextBox's text is bound to the FirstName property in your ViewModel -->
<TextBox Text="{Binding Path=FirstName}" />
<Button Command="{Binding SaveCommand}"/>

<!-- ViewModel: Expose a property for the TextBox to bind to -->
public string FirstName{ get; set; }
...
private void Save()
{
    //textBox's text is bound to --> this.FirstName;
}
于 2009-05-28T17:59:25.710 に答える
1

私はまだコメントをすることを許可されていません。試してみたので、カルロスの提案に応えています。素晴らしいアイデアですが、DelegateCommand を何らかの方法で変更する必要があります。そうしないと、次のエラーが発生するためです: フィールド初期化子は非静的フィールド、メソッド、またはプロパティ 'MyViewModel.Save(string)' を参照できません。

于 2010-09-14T14:28:19.133 に答える