2010-09-24 42 views
14

Tôi làm cách nào để truy cập tài nguyên XAML WPF này theo chương trình?Tôi làm cách nào để truy cập tài nguyên XAML WPF này theo chương trình?

<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> 

và đây là mã mà tôi muốn truy cập. Lưu ý Tôi cần lập trình tạo các dòng:

// 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 

Trả lời

19

Tôi không chắc chắn đường dẫn đến Grid bạn tham chiếu trong xaml của bạn; Tuy nhiên, do XAML này:

<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> 

và đoạn mã sau sẽ kéo nguồn từ cả Wndow, và ListView:

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

Trong trường hợp này phương pháp này là trong mã cửa sổ đằng sau lớp

5

FrameworkElement lớp học có đối tượng công khai FindResource (object resourceKey);. Sử dụng phương pháp này để tìm kiếm tài nguyên.

Nguyên nhân this.Resources["checkbox"]sẽ không cung cấp cho bạn nguồn tài nguyên nếu nó được định nghĩa là một hệ thống các Resource Từ điển và App Tài Nhưng this.FindResource("checkbox"); sẽ làm việc ở đó quá.

Các vấn đề liên quan