[英]Converter not working when DataTemplate is loaded in code behind
我在后面的代码中加载了用于image列的datatemplate。 请参考以下代码段,
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;
但是我的转换器没有被调用。 我需要在该列的每一行中加载不同的图像。 我错过了什么吗? 请分享任何想法
您实例化了一个新的Binding
但从未使用过。 做这个:
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;
编辑:看看FrameworkElementFactory
。 在评论中说:
此类是通过编程方式创建模板的不推荐使用的方法,这些模板是FrameworkTemplate的子类,例如ControlTemplate或DataTemplate; 使用此类创建模板时,并非所有模板功能都可用。 以编程方式创建模板的推荐方法是使用XamlReader类的Load方法从字符串或内存流中加载XAML。
也许您应该按照推荐的方式进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.