2012-12-30 36 views
1

我有一個DataTemplate,它需要一個對象的事件處理程序。此DataTemplate包含在ResourceDictionary中。將事件處理程序添加到此模板的最佳方式是什麼?來自DataTemplate的WinRT事件處理

我試着在app.xaml.cs中定義事件處理程序,但處理程序沒有執行。在ResourceDictionary的文件後面創建代碼會導致在MergedDictionaries中的應用程序啓動過程中加載錯誤。

從GraphStyles.xaml

<DataTemplate x:Key="PieTemplate"> 
    <Grid HorizontalAlignment="Left" Width="350" Height="350" > 
     <Border> 
      <Charting:Chart 
      x:Name="PieChart" 
      Title="Play Attempts" 
      Margin="70,0" Loaded="PieChart_Loaded"> 
       <Charting:Chart.Series> 
        <Charting:PieSeries 
        Title="Attempts" 
        ItemsSource="{Binding Items}" 
        IndependentValueBinding="{Binding Name}" 
        DependentValueBinding="{Binding Value}" 
        IsSelectionEnabled="True" /> 
       </Charting:Chart.Series> 
      </Charting:Chart> 
     </Border> 
    </Grid> 
</DataTemplate> 

在App.Xaml.cs

private void PieChart_Loaded(object sender, RoutedEventArgs e) 
    { 
     var pieChart = sender as Chart; 
     var legendItems = ((PieSeries)pieChart.Series[0]).LegendItems; 

     foreach (LegendItem item in legendItems) 
     { 
      pieChart.LegendItems.Add(item); 
      pieChart.LegendStyle = item.Style; 
     } 
    } 

回答

0

選項1

據我所知,你必須引用的DataTemplate中頂部的page/usercontrol的資源。使用合併的字典,以便仍然可以使用graphstyles.xaml。

如果你感到不舒服,因爲這傷了你的慣例,有一個相當長的嗦替代:

選項2

  1. 使用的MVVM視圖模型,並設置頁面/用戶控件的DataContext。
  2. 將數據模板保存在graphstyles.xaml中,並使用Attached Behavior鉤住Loaded事件,並將事件觸發器傳遞給viewmodels命令。
  3. 在ViewModel中創建一個UI可以響應的事件,然後鉤住它並在視圖代碼隱藏中進行處理。

我必須說我對選項2沒有生氣,因爲它有點破壞某些視圖/虛擬機的分離,但它應該完成工作 - 請注意,您必須將圖表作爲對象通過附加行爲,然後返回視圖模型,然後再將其轉換回圖表。

+0

我去了選項#2。它確實打破了分離,但我希望這是一個臨時解決方案。我正在使用這種技術來解決WinTxamltoolkit的餅圖實現中的一個錯誤。 –

相關問題