イベントをコマンドに結び付ける 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>