我正在模仿AttachedCommandBehavior library here来模拟一个附加的命令模式。我的按钮看起来像这样:
<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>一切都运行得很好,但是当执行Behavior上的setter时,命令是null。
Behavior是一个Freezable,而Behaviors是一个FreezableCollection<Behavior>。它似乎并没有从按钮继承DataContext。
另一方面,这是正确的:
<Button>
<vms:Attached.Behaviors>
<vms:Behavior Event="Click" Command="{Binding ClickCommand}" />
</vms:Attached.Behaviors>
</Button>不幸的是,我不能这样做,因为我需要使用ItemContainerStyle来定位生成的ListViewItem。
有没有什么方法可以让DataContext变得流行起来?
发布于 2011-02-06 07:58:17
附加的命令行为库是混合行为思想的萌芽。混合行为更加强大和标准化,因此我建议您切换到使用它们。但是,无论您使用的是附加命令行为还是混合行为,问题都是相同的:当尝试使用样式设置它们时,它们不能按预期工作。在这个StackOverflow答案中,我已经解决了混合行为的这个问题,完全支持绑定:
在不进行测试的情况下,我猜您必须将ACB行为移动到标记为x:Shared="False"的资源,以便使绑定工作。
发布于 2012-02-20 13:11:34
我也遇到了同样的问题,使用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>显然,您必须根据您的特定情况调整Relative Source的参数。无论出于何种原因,附加的属性似乎都不会继承数据上下文,因此您必须说明如何继承。
https://stackoverflow.com/questions/4909848
复制相似问题