2010-09-24 50 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");将在那里工作过的层次结构。

相关问题