在代码后面从ResourceDictionary访问DataTemplate

时间:2017-08-28 12:53:44

标签: wpf datatemplate resourcedictionary

我正在尝试将供应商提供的VB解决方案转换为C#。我需要将DataTemplate从自定义ResourceDictionary XAML加载到c#类中。我无法确定如何获取DataTemplate。我能够创建一个ResourceDictionary并加载XAML但是从那里难倒。这是我的XAML [EditorResources]。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:PropertyEditing="clr-namespace:Microsoft.Windows.Design.PropertyEditing;assembly=Microsoft.Windows.Design.Interaction"
                    xmlns:Local="clr-namespace:MyControls.Design"
                    xmlns:my="clr-namespace:MyControls;assembly=MyControls"
                    x:Class="EditorResources">
    <DataTemplate x:Key="TagBrowserInlineEditorTemplate">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <TextBox Grid.Column="0" Text="{Binding StringValue}"/>
            <PropertyEditing:EditModeSwitchButton Grid.Column="1"/>
        </Grid>
    </DataTemplate>

    <DataTemplate x:Key="template">
        <Border BorderThickness="2" 
                BorderBrush="Black">
            <TextBlock Text="{Binding Path=value}" Padding="2" />
        </Border>
    </DataTemplate>

</ResourceDictionary>

这是我需要转换的VB代码:

Imports System
Imports System.ComponentModel
Imports System.Windows
Imports Microsoft.Windows.Design.Metadata
Imports Microsoft.Windows.Design.PropertyEditing
Imports Microsoft.Win32

Public Class TagBrowserDialogPropertyValueEditor
    Inherits DialogPropertyValueEditor
    Private res As New EditorResources()

    Public Sub New()
        Me.InlineEditorTemplate = TryCast(res("TagBrowserInlineEditorTemplate"), DataTemplate)
    End Sub

    Public Overloads Overrides Sub ShowDialog(ByVal propertyValue As PropertyValue, ByVal commandSource As IInputElement)
        Dim frmBrowseTagParameter As New OPCWPFDashboard.Design.FormBrowseTagParameter
        If frmBrowseTagParameter Is Nothing Then
            frmBrowseTagParameter = New OPCWPFDashboard.Design.FormBrowseTagParameter
        End If

        If frmBrowseTagParameter.ShowDialog = Forms.DialogResult.OK Then
            propertyValue.StringValue = frmBrowseTagParameter.Final_Tag
        End If

    End Sub


End Class

2 个答案:

答案 0 :(得分:0)

WPF中的框架元素包含FindResource方法,该方法按键在应用程序范围内搜索资源。

查看documentation。您可以通过Key获取DataTemplate,然后在代码隐藏文件中访问它。

在这种情况下,这会对你有什么帮助吗?如果没有,请说明您的问题。

答案 1 :(得分:0)

据我了解,res变量是从ResourceDictionary派生的类的实例。在这种情况下,您可以非常轻松地获取数据模板:

this.InlineEditorTemplate = res["TagBrowserInlineEditorTemplate"] as DataTemplate;

有关更完整的示例,请参阅following article