2011-02-05 117 views
0

我在AttachedCommandBehavior library here之后为连接的命令模式建模。我的按钮看起来是这样的:WPF - 冻结在不继承DataContext的按钮样式中

<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设置方法时,该命令是null

行为是Freezable,行为是FreezableCollection<Behavior>。它似乎不是从Button继承DataContext。

在另一方面,这正常工作:

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

可惜我不能做这种方式,因为我需要使用ItemContainerStyle对象发出ListViewItem秒。

是否有某种方法可以在样式中获取DataContext?

+0

您的链接无效。你能编辑和修复吗? – Robaticus 2011-02-05 21:58:35

+0

糟糕,现在已经修好了。 – Snea 2011-02-05 22:06:04

回答

1

附加命令行为库是成为Blend Behaviors的想法的萌芽。混合行为功能更加强大和标准化,所以我建议您切换到使用它们。但是,无论您是使用“附加命令行为”还是“混合行为”,问题都是基本相同的:尝试使用样式设置它们时,它们无法按预期工作。我已经解决了这个问题并完全支持混合行为对该StackOverflow的答案绑定:

没有测试它,我想你必须移动ACB行为的资源标记x:Shared="False"为了获得绑定的工作。

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> 

你显然必须根据您的具体情况调整相对来源的参数。看来,无论出于何种原因,附加属性都不会继承数据上下文,因此您必须告知如何执行。