2010-09-24 48 views
14

我將如何編程方式訪問這個WPF XAML資源?我將如何編程方式訪問這個WPF XAML資源?

<Grid.Resources> 
<Style x:Key="lineDataPointStyle" TargetType="chartingToolkit:LineDataPoint"> 
         <Setter Property="Background" Value="DarkGreen"/> 
         <Setter Property="IsTabStop" Value="False"/> 
         <Setter Property="Template" Value="{x:Null}"/> 
        </Style> 
</Grid.Resources> 

這裏是我想從中訪問它的代碼。注意:我需要以編程方式創建行:

// New Assoicated Graph Series 
       var lineSeries = new LineSeries(); 
       lineSeries.ItemsSource = newSeriesCollection; 
       lineSeries.IndependentValuePath = "Second"; 
       lineSeries.DependentValuePath = "Kb"; 
       lineSeries.Title = kvp.Key; 
       lineSeries.DataPointStyle = (Style) this.Resources["lineDataPointStyle"]; // ** DOES NOT WORK 

回答

19

我不知道的路徑,你指的是你的XAML電網的;然而,鑑於此XAML:

<Window x:Class="WpfApplication1.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:src="clr-namespace:WpfApplication1" 
    Title="Test Application - ListView" Height="300" Width="300"> 
    <Window.Resources> 
     <src:OrderStateConverter x:Key="orderStateConverter"/> 
     <DataTemplate x:Key="checkbox"> 
      <CheckBox IsChecked="{Binding [email protected], Converter={StaticResource orderStateConverter}}" 
        Margin="0,1,1,1" > 
      </CheckBox> 
     </DataTemplate> 
     <DataTemplate x:Key="headerButton"> 
      <Button/> 
     </DataTemplate> 
    </Window.Resources> 
    <StackPanel> 
     <ListView Height="Auto" 
        Name="listView1" 
        Width="Auto" 
        ItemsSource="{Binding Source={StaticResource myXmlDatabase},XPath=Item}"> 
      <ListView.Resources> 
       <DataTemplate x:Key="checkbox2"> 
        <CheckBox IsChecked="{Binding [email protected], Converter={StaticResource orderStateConverter}}" 
        Margin="0,1,1,1" > 
        </CheckBox> 
       </DataTemplate> 
      </ListView.Resources> 
     </ListView> 
    </StackPanel> 
</Window> 

和下面的代碼將同時從Wndow,和ListView的拉動資源:

public void SomeMethod() { 
     Object res1 = this.Resources["checkbox"]; 
     Object res2 = this.listView1.Resources["checkbox2"]; 
     return; 
    } 

在這種情況下,方法是在窗口後面的代碼

5

FrameworkElement的類有公共對象FindResource(對象的ResourceKey);方法。使用此方法搜索資源。

原因this.Resources["checkbox"]不會給你如果資源 被定義爲資源字典和應用資源 但是,this.FindResource("checkbox");將在那裏工作過的層次結構。