簡體   English   中英

我將如何以編程方式訪問此WPF XAML資源?

[英]how would I access this WPF XAML resource programmatically?

我將如何以編程方式訪問此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

我不確定您在xaml中引用的Grid的路徑; 但是,考慮到這個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 XPath=@State, 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 XPath=@State, 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;
    }

在這種情況下,該方法位於類后面的窗口代碼中

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

導致this.Resources["checkbox"] 將不會為您提供資源,如果它被定義是資源字典和應用程序資源的層次結構但是this.FindResource("checkbox"); 也會在那里工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM