我将如何以编程方式访问此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>
Run Code Online (Sandbox Code Playgroud)
这是我想从中访问它的代码.注意我需要以编程方式创建行:
// 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
Run Code Online (Sandbox Code Playgroud)
Ste*_*ger 21
我不确定您在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>
Run Code Online (Sandbox Code Playgroud)
以下代码将从Wndow和ListView中提取资源:
public void SomeMethod() {
Object res1 = this.Resources["checkbox"];
Object res2 = this.listView1.Resources["checkbox2"];
return;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,该方法位于类后面的窗口代码中
FrameworkElement类有公共对象FindResource(对象resourceKey); 方法.使用此方法搜索资源.
this.Resources["checkbox"]如果定义的是资源字典和应用程序资源的层次结构,则原因不会为您提供资源 但this.FindResource("checkbox");也会在那里工作.