2012-11-26 44 views
1

Hallo我有一個事件集的問題。
我的窗口:WPF Treeview風格EventSetter不工作

<TreeView.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary 
       Source="CrefoChartTreeViewItemStyle.xaml" /> 
     </ResourceDictionary.MergedDictionaries> 
     <HierarchicalDataTemplate 
      DataType="{x:Type local:Node}" 
      ItemsSource="{Binding ChildNodes}"> 
     </HierarchicalDataTemplate> 
    </ResourceDictionary> 
</TreeView.Resources> 

我CrefoChartTreeViewItemStyle.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing" 
mc:Ignorable="d" 
> 
    <Style TargetType="TreeViewItem"> 
     <Style.Resources> 
      <LinearGradientBrush x:Key="ButtonBrush" EndPoint="0,1" StartPoint="0,0"> 
       <GradientStop Color="White" Offset="0.25"/> 
       <GradientStop Color="#FFA5DBE9" Offset="1"/> 
      </LinearGradientBrush> 
      <Style x:Key="ButtonStyle" TargetType="{x:Type Button}"> 
       <Setter Property="Background" Value="{DynamicResource ButtonBrush}" /> 
       <EventSetter Event="Click" Handler="ButtonOnClick" /> 
      </Style> 
     </Style.Resources> 

我收到錯誤消息當我編譯:

The event 'click' can not be specified on a Target tag in a Style. Instead, use "EventSetter". 

我該怎麼辦錯了嗎?

是否有任何其他方式來觸發樹視圖中的此按鈕?所以我可以把代碼放在後面?

回答

1

這不起作用 因爲資源xaml不能在文件 後面有代碼,所以它們通常稱爲「鬆散xaml」。你可以在關於EventSetter的msdn中閱讀。你可以做什麼並且應該做的是使用一些將你的事件轉換成命令的東西,比如AttachedCommandBehavior這個和MVVM很好地結合在一起。如果你想使用你所要求的事件,你可以把TreeView放在UserControl中,然後你可以使用事件。

+0

我不同意 - 資源字典xamls *可以*有一個代碼隱藏文件。你可以在[這個SO問題]中閱讀它(http://stackoverflow.com/questions/92100/is-it-possible-to-set-code-behind-a-resource-dictionary-in-wpf-for-事件handlin)和[這個SO問題](http://stackoverflow.com/questions/7045718/wpf-events-in-resourcedictionary-for-a-controltemplate)(可能更多)。 –

+0

@ O.R.Mapper好的你是對的,如果你走得那麼遠,這是可能的。但我會說它不是常規的情況。 – dowhilefor