我该如何在程序中访问这个WPF XAML资源?

17

我该如何在程序中访问这个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
2个回答

22

我不确定您在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 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>

以下代码将从 Window 和 ListView 中提取资源:

    public void SomeMethod() {
        Object res1 = this.Resources["checkbox"];
        Object res2 = this.listView1.Resources["checkbox2"];
        return;
    }
在这种情况下,该方法在窗口代码后端类中。

7

FrameworkElement类有一个public object FindResource(object resourceKey);方法。使用此方法搜索资源。

如果资源在资源字典层次结构和应用程序资源中定义,则this.Resources["checkbox"]将不会给您资源,但是this.FindResource("checkbox");也可以在那里工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接