0

我在此处的 AttachedCommandBehavior 库之后对附加命令模式进行建模。我的按钮如下所示:

<Button>
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="vms:Attached.Behaviors">
                <Setter.Value>
                    <vms:Behaviors>
                        <vms:Behavior Event="Click" 
                                      Command="{Binding ClickCommand}" />
                    </vms:Behaviors>
                </Setter.Value>
            </Setter>
        </Style>
    </Button.Style>
</Button>

一切都很好,但是当执行 setter 时Behavior,命令是null.

行为是一个Freezable,行为是一个FreezableCollection<Behavior>。它似乎没有从 Button 继承 DataContext。

另一方面,这可以正常工作:

<Button>
    <vms:Attached.Behaviors>
        <vms:Behavior Event="Click" Command="{Binding ClickCommand}" />
    </vms:Attached.Behaviors>
</Button>

不幸的是,我不能这样做,因为我需要ListViewItem使用ItemContainerStyle.

有什么方法可以在 Style 中获取 DataContext 吗?

4

2 回答 2

1

附加命令行为库是成为混合行为的想法的萌芽。混合行为更加强大和标准化,因此我建议您改用它们。但无论您使用的是附加命令行为还是混合行为,问题本质上都是相同的:尝试使用样式设置它们时,它们无法按预期工作。我已经解决了 Blend Behaviors 的这个问题,完全支持这个 StackOverflow 答案中的绑定:

如果不对其进行测试,我想您必须将 ACB 行为移动到标记为的资源x:Shared="False"才能使绑定起作用。

于 2011-02-05T23:58:17.470 回答
0

我遇到了同样的问题,使用 RelativeSource 就可以了。我会告诉你我之前和之后的代码......

之前:(这不起作用)

<DataTemplate x:Key="MenuNodeWithChildrenTemplate">
    <StackPanel Orientation="Horizontal"
            behaviors:EventCommand.CommandToRun="{Binding OpenMenuItem}"
            behaviors:EventCommand.EventName="MouseLeftButtonUp">
        <Label Content="{Binding Title}"/>
        <Label Content="{Binding Description}"/>
    </StackPanel>
</DataTemplate>

之后:(这确实有效)

<DataTemplate x:Key="MenuNodeWithChildrenTemplate">
    <StackPanel Orientation="Horizontal"
            behaviors:EventCommand.CommandToRun="{Binding Path=DataContext.OpenMenuItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemsControl}}}"
            behaviors:EventCommand.EventName="MouseLeftButtonUp">
        <Label Content="{Binding Title}"/>
        <Label Content="{Binding Description}"/>
    </StackPanel>
</DataTemplate>

您显然必须根据您的具体情况调整相对源的参数。似乎,无论出于何种原因,附加属性都不会继承数据上下文,所以你必须知道如何去做。

于 2012-02-20T05:11:33.923 回答