2011-02-05 118 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> 

你顯然必須根據您的具體情況調整相對來源的參數。看來,無論出於何種原因,附加屬性都不會繼承數據上下文,因此您必須告知如何執行。