3

イベントをコマンドに結び付ける MVVM ヘルパー クラスとして使用される添付プロパティ AttachedBehaviorsManager.Behaviors を作成しました。プロパティのタイプは BehaviorCollection (ObservableCollection のラッパー) です。私の問題は、動作のコマンドのバインディングが常に null になってしまうことです。ボタンで使用すると、問題なく動作します。

私の質問は、コレクション内のアイテムで DataContext が失われるのはなぜですか?どうすれば修正できますか?

<UserControl x:Class="SimpleMVVM.View.MyControlWithButtons"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:behaviors="clr-namespace:SimpleMVVM.Behaviors"
             xmlns:con="clr-namespace:SimpleMVVM.Converters"
Height="300" Width="300">
<StackPanel>
        <Button Height="20" Command="{Binding Path=SetTextCommand}" CommandParameter="A" Content="Button A" />
     <Button Height="20" Command="{Binding Path=SetTextCommand}" CommandParameter="B" Content="Button B"/>
    <TextBox x:Name="tb" Text="{Binding Path=LabelText}">
        <behaviors:AttachedBehaviorsManager.Behaviors>
            <behaviors:BehaviorCollection>
                <behaviors:Behavior Command="{Binding Path=SetTextCommand}" CommandParameter="A" EventName="GotFocus"/>
            </behaviors:BehaviorCollection>
        </behaviors:AttachedBehaviorsManager.Behaviors>
    </TextBox>
</StackPanel>

4

2 に答える 2

0

これは MVVM ( Model-View-ViewModel ) パターンを使用しているため、コマンドにバインドします。このユーザー コントロールのデータ コンテキストは、コマンドを公開するプロパティを含む ViewModel オブジェクトです。コマンドは public static オブジェクトである必要はありません。

表示されたコードのボタンは実行に問題はありません。ビューモデルの SetTextCommand にバインドされています。

class MyControlViewModel : ViewModelBase
{
    ICommand setTextCommand;
    string labelText;

    public ICommand SetTextCommand
    {
        get
        {
            if (setTextCommand == null)
                setTextCommand = new RelayCommand(x => setText((string)x));
            return setTextCommand;
        }
    }
    //LabelText Property Code...

    void setText(string text)
    {
        LabelText = "You clicked: " + text;
    }
}

問題は、ボタンで機能する同じ SetTextCommand へのバインドが、behavior:Behavior で認識されないことです。

于 2009-05-06T20:18:35.133 に答える
0

なぜあなたはコマンドにバインドしていますか? コマンドは、次のようにセットアップすることを意図しています。

<Button Command="ApplicationCommands.Open"/>

次のようにコマンド クラスを定義するとします。

namespace SimpleMVVM.Behaviors {
    public static class SimpleMvvmCommands {
        public static RoutedUICommand SetTextCommand { get; }
    }
}

次のように使用します。

<Button Command="behaviors:SimpleMvvmCommands.SetTextCommand"/>

MVVM パターンは、使用している方法には適用できません。コマンド ハンドラーは VM に配置しますが、コマンド自体は静的なコンテキストにあることを意図しています。詳細については、 MSDNのドキュメントを参照してください。

于 2009-05-05T18:30:16.680 に答える