我在XAML中定义了具有代码隐藏的ResouceDictionary。我需要使用鼠标事件和数据绑定来定义一些视图特定的行为,为此我需要访问DataTemplate中定义的一些元素。当DataTemplate没有密钥时,从ResourceDictionary中访问DataTemplate只有TargetType
问题是,DataTemplate没有一个Key,它只有一个TargetType(WPF会自动将它用于给定类型)。
那么,如何从代码隐藏中访问DataTemplate?
编辑:
如果我在构造函数中放一个断点的地方,我可以看到我的ViewModel模板是存在的。看来,ResourceDictionary.Keys属性是对象的数组,并获得我想要的键(或相应的价值,实际上)就是这样在调试器:
{DataTemplateKey(Company.Application.ViewModels.TargetViewModel)}
XAML:
<sys:Double x:Key="escala">10</sys:Double>
<sys:Double x:Key="raio">20</sys:Double>
<EllipseGeometry x:Key="geometriacirculo"
RadiusX="{StaticResource raio}"
RadiusY="{StaticResource raio}"/>
<ScaleTransform x:Key="transform" ScaleX="{StaticResource escala}" ScaleY="{StaticResource escala}" />
<ap:NormalConverter x:Key="NormalConverter"/>
<ap:BitmapToSource x:Key="BitmapToSource"/>
<DataTemplate DataType="{x:Type vm:TelaColetaViewModel}">
<.....
代码隐藏:
public partial class TelaColetaTemplate : ResourceDictionary
{
EllipseGeometry _geometria_circulo;
ScaleTransform _scale_transform;
Grid GridZoom;
Path CirculoGuia;
double _escala;
Point? _ponto_clicado_norm;
public TelaColetaTemplate()
{
InitializeComponent();
// three following lines work, accessing them with key, no problem
_geometria_circulo = (EllipseGeometry)this["geometriacirculo"];
_scale_transform = (ScaleTransform)this["transform"];
_escala = (double)this["escala"];
//var wantedTemplate = ????
......
如果您使用的是'X:关键'你可以使用静态方法'FindResource'。我不知道“无名”DataTemplates。对不起 – Tico
@Tico如果您想要自动加载(而不是显式地)加载给定类型,则不要在DataTemplate中放置一个键,这是非常重要的。如果我放置一个断点,我可以看到隐式键,只是不知道如何访问它,请参阅我的编辑。 – heltonbiker
当我仅在XAML中使用'DataTemplates'时,从来没有在代码背后做过。但我确实使用上述方法应用资源。好问题,我会看这个线程。 – Tico