WPF using converter in datatemplate created from xaml text and XamlReader on phone 8

五迷三道 提交于 2019-12-23 05:27:56

问题


I'm generating a DataTemplate using a text xaml like this:

var dataTemplate = (DataTemplate)XamlReader.Load(xaml.ToString());

One of the elements is a CheckBox bound with it's converter pointing to a StaticResource:

    StringBuilder xaml = new StringBuilder();
    xaml.AppendFormat(@"          <CheckBox");
    xaml.AppendFormat(@" IsChecked=""{{Binding [{0}], Converter={{StaticResource stringValueToBoolConverter}}, Mode=TwoWay}}""", header.ID);
    xaml.AppendFormat(@" />");

The presence of this converter reference in the text causes an exception caught in the Application_UnhandledException on phone. The message looks like this:

-       InnerException  {System.Exception: Error HRESULT E_FAIL has been returned from a call to a COM component.
   at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
   at MS.Internal.XcpImports.UIElement_Measure_WithDesiredSize(UIElement element, Size availableSize)
   at System.Windows.UIElement.Measure_WithDesiredSize(Size availableSize)
   at System.Windows.Controls.VirtualizingStackPanel.MeasureChild(UIElement child, Size layoutSlotSize)
   at System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureOverride(IntPtr nativeTarget, Double inWidth, Double inHeight, Double& outWidth, Double& outHeight)}   System.Exception

The template is used to create a row in a listbox and the control has the converter declared in it's resources:

<UserControl.Resources>
        <converters:StringValueToBoolConverter x:Key="stringValueToBoolConverter" />
</UserControl.Resources>

I suppose that at some creation step, the object creation process of xaml->objects can't find the converter - is there a way to get around it?

**Addition

I also just tested adding a Loaded for the check box - same assert as adding the converter

StringBuilder xaml = new StringBuilder();
xaml.AppendFormat(@"          <CheckBox");
xaml.AppendFormat(@" IsChecked=""{{Binding [{0}],  Mode=TwoWay}}""", header.ID);
xaml.AppendFormat(@" Loaded=""FrameworkElement_OnLoaded""");

Maybe there's a way to provide this context to the loader?


回答1:


The template is used to create a row in a listbox and the control has the converter declared in it's resources:

Why not instead load the data into a preloaded listbox and use ItemsSource to bind to a collection loaded from your file? And use a visibility converter to show/hide date. What you're doing seems needlessly complicated for what it actually does.



来源:https://stackoverflow.com/questions/28350731/wpf-using-converter-in-datatemplate-created-from-xaml-text-and-xamlreader-on-pho

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