简体   繁体   English

在后面的代码中加载DataTemplate时,转换器不起作用

[英]Converter not working when DataTemplate is loaded in code behind

I loaded the datatemplate for image column in code behind . 我在后面的代码中加载了用于image列的datatemplate。 Please refer the below code snippet, 请参考以下代码段,

        FrameworkElementFactory fef = new FrameworkElementFactory(typeof(Image));
        Binding bind = new Binding() { Path=new PropertyPath(imagecolumn.MappingName),Converter = new StringToImageConverter(),Mode=BindingMode.TwoWay };         
        fef.SetBinding(Image.SourceProperty,new Binding(imagecolumn.MappingName));
        DataTemplate template = new DataTemplate() { VisualTree = fef };            
        this.imagecolumn.CellItemTemplate = template;          

But my converter is not invoked. 但是我的转换器没有被调用。 I need to load different images in each row of the column . 我需要在该列的每一行中加载不同的图像。 Am i missed anything ? 我错过了什么吗? Please share any idea 请分享任何想法

You instantiate a new Binding but you never use it. 您实例化了一个新的Binding但从未使用过。 Do this: 做这个:

    FrameworkElementFactory fef = new FrameworkElementFactory(typeof(Image));
    Binding bind = new Binding() { Path=new PropertyPath("MappingName"),Converter = new StringToImageConverter(),Mode=BindingMode.TwoWay,Source=imagecolumn };         
    fef.SetBinding(Image.SourceProperty, bind); // here you just created 
    //another instance of Binding instead  of using your bind variable
    DataTemplate template = new DataTemplate() { VisualTree = fef };            
    this.imagecolumn.CellItemTemplate = template;  

EDIT: Have a look at FrameworkElementFactory . 编辑:看看FrameworkElementFactory In the remarks it sais: 在评论中说:

This class is a deprecated way to programmatically create templates, which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate; 此类是通过编程方式创建模板的不推荐使用的方法,这些模板是FrameworkTemplate的子类,例如ControlTemplate或DataTemplate; not all of the template functionality is available when you create a template using this class. 使用此类创建模板时,并非所有模板功能都可用。 The recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class. 以编程方式创建模板的推荐方法是使用XamlReader类的Load方法从字符串或内存流中加载XAML。

Maybe you should do it the recommended way. 也许您应该按照推荐的方式进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM