3

我创建了一个附加属性 AttachedBehaviorsManager.Behaviors,它将用作将事件与命令联系起来的 MVVM 帮助器类。该属性属于 BehaviorCollection 类型(ObservableCollection 的包装器)。我的问题是行为命令的绑定总是最终为空。当在按钮上使用时,它工作得很好。

我的问题是为什么我在集合内的项目上丢失了我的 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

为什么要绑定命令?命令旨在以这种方式设置:

<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 回答
0

您绑定到命令,因为它使用 MVVM ( Model-View-ViewModel ) 模式。此用户控件的数据上下文是一个 ViewModel 对象,其中包含一个公开命令的属性。命令不需要是公共静态对象。

所示代码中的按钮执行没有问题。它们绑定到视图模型中的 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 的绑定:行为。

于 2009-05-06T20:18:35.133 回答