0

ビューには10個のボタンがあり、クリックするとViewModelの適​​切なプロパティをnullに設定する必要があります(ViewModelはViewのDataContextです)。リセット アクションのようなものと考えてください。

現在、私が持っているのはViewModelのICommandで、各ボタンのコマンドがバインドされています。次に、CommandParameterを何らかの値に設定します。これにより、ViewModelのどのプロパティを更新する必要があるかを区別できます。

たくさんのIfを避けるために、私は次のようなことを考えています(構文が正しくありません):

<Button ...>
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <Setter Property="PropertyA" Source="DataContext-ViewModel" Value="x:null" />
    </i:EventTrigger>
  <i:Interaction.Triggers>
</Button>

これを達成することは可能ですか?

4

1 に答える 1

0

オプションを使用する場合は、ViewModel でプロパティを設定するためにReflection使用できます。Reflection

コマンド実行メソッドは次のようになります。

this.GetType().GetProperty((string)CommandParameter).SetValue(this, null, new object[] {});

ただし、質問で言及した XAML ルートを使用する場合は、 を作成してで使用できます。以下は私が試したものです:TriggerActionEventTrigger

public sealed class SetProperty : TriggerAction<FrameworkElement>
{
    public static readonly DependencyProperty SourceProperty =
        DependencyProperty.Register("Source", typeof (object), typeof (SetProperty), new PropertyMetadata(default(object)));

    /// <summary>
    /// Source is DataContext
    /// </summary>
    public object Source
    {
        get { return (object) GetValue(SourceProperty); }
        set { SetValue(SourceProperty, value); }
    }

    public static readonly DependencyProperty PropertyNameProperty =
        DependencyProperty.Register("PropertyName", typeof (string), typeof (SetProperty), new PropertyMetadata(default(string)));

    /// <summary>
    /// Name of the Property
    /// </summary>
    public string PropertyName
    {
        get { return (string) GetValue(PropertyNameProperty); }
        set { SetValue(PropertyNameProperty, value); }
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof (object), typeof (SetProperty), new PropertyMetadata(default(object)));

    /// <summary>
    /// Value to Set
    /// </summary>
    public object Value
    {
        get { return (object) GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    protected override void Invoke(object parameter)
    {
        if (Source == null) return;
        if (string.IsNullOrEmpty(PropertyName)) return;

        Source.GetType().GetProperty(PropertyName).SetValue(Source, Value, new object[] {});
    }
}

および XAML:

<Button Content="Reset">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <local:SetProperty Source="{Binding}" PropertyName="PropertyToSet" Value="{x:Null}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

リフレクションがまったく気に入らない場合は、ビューモデルにアクションのディクショナリを含めることができます。

_propertyResetters = new Dictionary<string, Action>
{
    {"PropertyToSet", () => PropertyToSet = null}
};

そして、Command Execute メソッドで、これらのアクションを呼び出すことができます。_propertyResetters[(string)CommandParameter]();

これが役立つか、アイデアを提供してくれることを願っています。

于 2013-11-06T15:35:44.060 に答える