83

私はこのコードを持っています(これは正しく動作します):

<KeyBinding Key="Enter" Command="{Binding ReturnResultCommand}">
    <KeyBinding.CommandParameter>
        <s:Boolean>
            True
        </s:Boolean>
    </KeyBinding.CommandParameter>
</KeyBinding>

「s」はもちろんシステム名前空間です。

しかし、このコマンドはかなりの回数呼び出され、それ以外の場合はかなり単純な XAML コードを実際に膨らませます。これは本当に XAML のブール値コマンド パラメーターの最短表記ですか (コマンドを複数のコマンドに分割する以外は)?

4

6 に答える 6

118

これは少しハックかもしれませんが、KeyBindingクラスから派生させることができます:

public class BoolKeyBinding : KeyBinding
{
    public bool Parameter
    {
        get { return (bool)CommandParameter; }
        set { CommandParameter = value; }
    }
}

使用法:

<local:BoolKeyBinding ... Parameter="True"/>

そして、それほど奇妙ではない別の解決策:

xmlns:s="clr-namespace:System;assembly=mscorlib"
<Application.Resources>
    <!-- ... -->
    <s:Boolean x:Key="True">True</s:Boolean>
    <s:Boolean x:Key="False">False</s:Boolean>
</Application.Resources>

使用法:

<KeyBinding ... CommandParameter="{StaticResource True}"/>
于 2011-02-14T21:48:09.390 に答える
70

最も簡単な方法は、リソースで次のように定義することです

<System:Boolean x:Key="FalseValue">False</System:Boolean>
<System:Boolean x:Key="TrueValue">True</System:Boolean>

次のように使用します。

<Button CommandParameter="{StaticResource FalseValue}"/>
于 2012-11-09T17:47:25.810 に答える
26

このマークアップ拡張機能を使用して、さらに一般的なソリューションを見つけました。

public class SystemTypeExtension : MarkupExtension
{
    private object parameter;

    public int Int{set { parameter = value; }}
    public double Double { set { parameter = value; } }
    public float Float { set { parameter = value; } }
    public bool Bool { set { parameter = value; } }
    // add more as needed here

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return parameter;
    }
}

使用法 (「wpf:」は拡張機能が存在する名前空間です):

<KeyBinding Key="F8" Command="{Binding SomeCommand}" CommandParameter="{wpf:SystemType Bool=True}"/>

オプションTrueを取得し、False入力後にBool=安全性を入力することもできます!

于 2015-08-13T16:31:29.583 に答える
6

おそらく次のようなもの

<KeyBinding Key="Enter" Command="{Binding ReturnResultCommand}"
    CommandParameter="{x:Static StaticBoolean.True}" />

どこStaticBooleanですか

public static class StaticBoolean
{
    public static bool True
    {
        get { return true; }
    }
}
于 2011-02-14T21:40:07.207 に答える