2012-11-26 39 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