hel*_*ker 1 wpf code-behind resourcedictionary targettype
我在XAML中用代码隐藏了一个ResouceDictionary。我需要使用鼠标事件和数据绑定定义一些特定于视图的行为,为此,我需要访问在DataTemplate内部定义的某些元素。
问题是,DataTemplate没有Key,而只有TargetType(这是必需的,因此WPF会自动将其用于给定类型)。
那么,如何从代码隐藏访问DataTemplate?
编辑:
如果在构造函数中的某个地方放置断点,则可以看到ViewModel的模板在那里。似乎ResourceDictionary.Keys属性是一个对象数组,而我要访问的键(实际上是相应的值)在调试器中是这样的:
{DataTemplateKey(Company.Application.ViewModels.TargetViewModel)}
Run Code Online (Sandbox Code Playgroud)
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}">
<.....
Run Code Online (Sandbox Code Playgroud)
代码背后:
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 = ????
......
Run Code Online (Sandbox Code Playgroud)
DataTemplates与刚刚DataType提到的,但不会x:Key为它们创建一个隐式密钥。因此,从本质上讲,进入您的DataTemplate所需要做的就是创建一个DataTemplate Key并将其用作索引器参数ResourceDictionary
下面的示例代码:
new DataTemplateKey(typeof(TargetViewModel));
Run Code Online (Sandbox Code Playgroud)