dynamic datatemplate with valueconverter

China☆狼群 提交于 2019-12-02 04:13:58

For whatever reason, it works as expected if I do like this...

    string assName = Assembly.GetExecutingAssembly().GetName().Name;
    StringBuilder sb = new StringBuilder();
    sb.Append("<DataTemplate ");
    sb.Append("xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' ");
    sb.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
    sb.Append("xmlns:src='clr-namespace:WpfToolkitDataGridTester;assembly=" + assName + "' >");
    sb.Append("<DataTemplate.Resources>");
    sb.Append("<src:FooConverter x:Key='fooConverter' />");
    sb.Append("</DataTemplate.Resources>");
    sb.Append("<TextBlock ");
    sb.Append("Foreground='{Binding Candidates[" + i + "].CandidateType,Converter={StaticResource fooConverter}}' ");
    sb.Append("Text='{Binding Candidates[" + i + @"].Name}' />");
    sb.Append("</DataTemplate>");
    var template = (DataTemplate)XamlReader.Parse(sb.ToString());

When the XAML files are compiled to BAML it references the assembly not the in memory source. Since the BAML is compiled into the same assembly the actual type isn't available yet.

I've found that a short term workaround is to comment out the style temporarily, build the project, then restore the style.

The more permanent solution however is to move the converter to another assembly.

Would it help to declare the FooConverter once at a higher level (maybe as a resource of the DataGrid) instead of in each DataTemplate?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!