コード例 #1
0
        public void LoadConfigXML(string configXML)
        {
            var element = XElement.Parse(configXML);

            foreach (var el in element.Elements())
            {
                //this should be 1st-level decendants
                Control configuredControl = XamlReader.Parse(el.ToString()) as Control;

                var win = Window.GetWindow(this);

                configuredControl.LoadConfiguration(win);
            }
        }
コード例 #2
0
        public TodoListClass GetXmlObject(string XamlPath)
        {
            try
            {
                string xaml = File.ReadAllText(XamlPath);

                TodoListClass r = (TodoListClass)XamlReader.Parse(xaml);
                return(r);
            }
            catch
            {
                return(null);
            }
        }
コード例 #3
0
    private DataTemplate CreateTemplate(string path)
    {
        string xamlTemplate = string.Format("<DataTemplate><ContentPresenter Content=\"{{Binding {0}}}\" ContentTemplate=\"{{StaticResource GridViewTextCell}}\" /></DataTemplate>", path);
        var    context      = new ParserContext
        {
            XamlTypeMapper = new XamlTypeMapper(new string[0])
        };

        context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
        context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
        var template = (DataTemplate)XamlReader.Parse(xamlTemplate, context);

        return(template);
    }
コード例 #4
0
 private void PreviewOnRichTextBox_Click(object sender, RoutedEventArgs e)
 {
     OutputBox.Text = string.Empty;
     try
     {
         PreviewRichTextBox.Document = XamlReader.Parse(XamlBox.Text) as FlowDocument;
         var start = PreviewRichTextBox.Document.ContentStart;
         //PreviewTreeView.ItemsSource = GetTreeItem(PreviewRichTextBox.Document, ref start);
     }
     catch (Exception ex)
     {
         OutputBox.Text = ex.ToString();
     }
 }
コード例 #5
0
        private static DataTemplate CreateContentTemplate()
        {
            const string xaml =
                "<DataTemplate><Border b:TabContent.InternalTabControl=\"{Binding RelativeSource={RelativeSource AncestorType=TabControl}}\" /></DataTemplate>";
            var context = new ParserContext();

            context.XamlTypeMapper = new XamlTypeMapper(new string[0]);
            context.XamlTypeMapper.AddMappingProcessingInstruction("b", typeof(TabContent).Namespace, typeof(TabContent).Assembly.FullName);
            context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
            context.XmlnsDictionary.Add("b", "b");
            var template = (DataTemplate)XamlReader.Parse(xaml, context);

            return(template);
        }
コード例 #6
0
 public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     if (value is string)
     {
         try
         {
             return(XamlReader.Parse(string.Format(@"<CornerRadius xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>{0}</CornerRadius>", value)));
         }
         catch
         {
         }
     }
     return(value);
 }
コード例 #7
0
        public void VerifyRepeaterDoesNotLeakItemContainers()
        {
            ObservableCollection <int> items = new ObservableCollection <int>();

            for (int i = 0; i < 10; i++)
            {
                items.Add(i);
            }

            ItemsRepeater repeater = null;

            RunOnUIThread.Execute(() =>
            {
                var template = (DataTemplate)XamlReader.Parse("<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' "
                                                              + "xmlns:local='clr-namespace:MUXControlsTestApp.Samples;assembly=MUXControlsTestApp'>"
                                                              + "<local:DisposableUserControl Number='{Binding}'/>"
                                                              + "</DataTemplate>");
                Verify.IsNotNull(template);
                Verify.AreEqual(0, MUXControlsTestApp.Samples.DisposableUserControl.OpenItems, "Verify we start with 0 DisposableUserControl");

                repeater = new ItemsRepeater()
                {
                    ItemsSource         = items,
                    ItemTemplate        = template,
                    VerticalAlignment   = VerticalAlignment.Top,
                    HorizontalAlignment = HorizontalAlignment.Left
                };

                Content = repeater;
            });

            IdleSynchronizer.Wait();

            RunOnUIThread.Execute(() =>
            {
                Verify.IsGreaterThanOrEqual(MUXControlsTestApp.Samples.DisposableUserControl.OpenItems, 10, "Verify we created at least 10 DisposableUserControl");

                // Clear out the repeater and make sure everything gets cleaned up.
                Content  = null;
                repeater = null;
            });

            IdleSynchronizer.Wait();

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            Verify.AreEqual(0, MUXControlsTestApp.Samples.DisposableUserControl.OpenItems, "Verify we cleaned up all the DisposableUserControl that were created");
        }
コード例 #8
0
ファイル: Misc.cs プロジェクト: panta82/delta_draw
 public static object ReadFromXaml(string xaml)
 {
     try
     {
         ParserContext parserContext = new ParserContext();
         parserContext.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
         parserContext.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
         return(XamlReader.Parse(xaml, parserContext));
     }
     catch (Exception)
     {
         return(null);
     }
 }
コード例 #9
0
ファイル: MainWindow.xaml.cs プロジェクト: JawadJaber/WPF2PDF
 private void ParseButton_OnClick(object sender, RoutedEventArgs e)
 {
     using (var stream = new FileStream("Templates\\report1.lqd", FileMode.Open))
     {
         using (var reader = new StreamReader(stream))
         {
             var templateString = reader.ReadToEnd();
             var template       = dotTemplate.Parse(templateString);
             var docContext     = CreateDocumentContext();
             var docString      = template.Render(docContext);
             DocViewer.Document = (FlowDocument)XamlReader.Parse(docString);
         }
     }
 }
コード例 #10
0
        public void GetDefaultBoardData()
        {
            try
            {
                if (_rethinkCon != null && _rethinkCon.Open)
                {
                    var strokesData   = _rethinkDb.Db(_rethinkDatabase).Table(_rethinkAnnotations).Filter(k => k.G("MeetingId").Eq(_meetingId)).Run(_rethinkCon);
                    var resourcesData = _rethinkDb.Db(_rethinkDatabase).Table(_rethinkResources).Filter(k => k.G("MeetingId").Eq(_meetingId)).Run(_rethinkCon);

                    NxgUtilities.CreateDirectory(Constants.AttachmentResources + _meetingId);
                    foreach (var data in resourcesData.BufferedItems)
                    {
                        RtLibraryThumb resource = JsonConvert.DeserializeObject <RtLibraryThumb>(Convert.ToString(data));
                        string         filePath = Constants.AttachmentResources + _meetingId + "/" + resource.FileId + ".png";
                        if (!File.Exists(filePath))
                        {
                            NxgUtilities.GetBitmapFromBytes(Convert.FromBase64String(resource.BinaryData), filePath);
                        }
                    }

                    if (strokesData.BufferedItems.Count > 0)
                    {
                        foreach (var item in strokesData.BufferedItems)
                        {
                            RtBoardAnnotation annotations = JsonConvert.DeserializeObject <RtBoardAnnotation>(Convert.ToString(item));
                            if (annotations != null && !string.IsNullOrWhiteSpace(annotations.Strokes) && annotations.MeetingId == _meetingId)
                            {
                                App.Current.Dispatcher.Invoke(() =>
                                {
                                    try
                                    {
                                        StrokeCollection strokes = XamlReader.Parse(annotations.Strokes) as StrokeCollection;
                                        _guestInkCanvas.Strokes  = new StrokeCollection(strokes.Where(s => Convert.ToString(s.GetPropertyData(s.GetPropertyDataIds()[0])) != _macAddress).ToList());
                                        _boardInkCanvas.Strokes  = new StrokeCollection(strokes.Where(s => Convert.ToString(s.GetPropertyData(s.GetPropertyDataIds()[0])) == _macAddress).ToList());
                                    }
                                    catch (Exception)
                                    {
                                    }
                                });
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                App.InsertException(ex);
            }
        }
コード例 #11
0
        /// <summary>
        /// When the page is loaded, retrieve the persisted column layout
        /// This is a pretty grubby way of doing things but I couldn't think
        /// of anything better :/
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            //this event will fire not only when is first shown, but every time its shown
            // eg when switching between tabs.  Not sure why
            if (_loaded)
            {
                return;
            }

            //fetch the layout from settings
            string xaml = Properties.Settings.Default.SearchColumns;

            if (!String.IsNullOrEmpty(xaml))
            {
                GridViewColumnCollection savedCols    = XamlReader.Parse(xaml) as GridViewColumnCollection;
                GridViewColumnCollection gridViewCols = ((GridView)listView1.View).Columns;

                //we can't share GridViewColumns between collections, nor can we
                //remove one during a foreach, so we have to copy them to a list,
                //then add them to the collection.
                List <GridViewColumn> tempCols = new List <GridViewColumn>();

                foreach (GridViewColumn col in savedCols)
                {
                    tempCols.Add(col);
                }

                gridViewCols.Clear();
                savedCols.Clear();

                //TODO: we should be using the existing converter resource rather than making a new one
                BooleanToVisibilityConverter boolToVisCon = new BooleanToVisibilityConverter();

                foreach (GridViewColumn col in tempCols)
                {
                    //add the templates, bindings, and set the visible states as these aren't persisted
                    col.HeaderTemplate = listView1.TryFindResource("HeaderTemplateSortNon") as DataTemplate;
                    GridViewColumnHeader gvch = col.Header as GridViewColumnHeader;
                    MenuItem             mnu  = this.FindName("mnuCol" + gvch.Content.ToString()) as MenuItem;
                    mnu.IsChecked = (gvch.Visibility == System.Windows.Visibility.Visible);
                    Binding b = new Binding("IsChecked");
                    b.ElementName = "mnuCol" + gvch.Content.ToString();
                    b.Converter   = boolToVisCon;
                    gvch.SetBinding(UIElement.VisibilityProperty, b);
                    gridViewCols.Add(col);
                }
            }
            _loaded = true;
        }
コード例 #12
0
        /// <summary>
        /// Reads the XAML input in the specified text string and returns a <see cref="Span"/> wrapping the an object that
        /// corresponds to the root of the specified markup.
        /// <para/>
        /// Be careful using this feature in UWP release. Behaviours, action and converters does not work most of the time.
        /// </summary>
        /// <param name="xamlText">The input XAML, as a single text string.</param>
        /// <returns>The <see cref="Span"/> root of the created object tree.</returns>
        public static Span ParseToInline(string xamlText)
        {
            if (xamlText == null)
            {
                throw new ArgumentNullException(nameof(xamlText));
            }

#if WINDOWS_UWP
            var xmlns = new string[] /* Will not work in UWP Release */
            {
                @"xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""",
                @"xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""",
                @"xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006""",
                @"xmlns:d=""http://schemas.microsoft.com/expression/blend/2008""",
                @"xmlns:controls=""using:Cauldron.XAML.Controls""",
            }.Join(" ");
#else
            var xmlns = new string[]
            {
                "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\""
            }.Join(" ");
#endif

            var xaml = xamlText.Replace("<Inline>\r\n", $"<Span {xmlns}>")
                       .Replace("\r\n</Inline>", "</Span>")
                       .Replace("<Inline>", $"<Span {xmlns}>")
                       .Replace("</Inline>", "</Span>")
                       .Replace("''", "\"")
                       .Replace("\r\n", "<LineBreak/>")
                       .Replace("<br>", "<LineBreak/>")
                       .Replace(@"\r\n", "<LineBreak/>")
                       .Replace(@"\n\n", "<LineBreak/><LineBreak/>");
            try
            {
#if WINDOWS_UWP
                return(XamlReader.Load(xaml) as Span);
#else
                return(XamlReader.Parse(xaml) as Span);
#endif
            }
            catch (Exception e)
            {
                var span = new Span();
                span.Inlines.Add(new Run {
                    Text = e.Message
                });
                return(span);
            }
        }
コード例 #13
0
        public object GetDataTemplate(Type viewType)
        {
            string xaml = string.Format("<DataTemplate><v:{0} /></DataTemplate>", viewType.Name);

            ParserContext context = new ParserContext();

            context.XamlTypeMapper = new XamlTypeMapper(new string[0]);
            context.XamlTypeMapper.AddMappingProcessingInstruction("v", viewType.Namespace, viewType.Assembly.FullName);

            context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
            context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
            context.XmlnsDictionary.Add("v", "v");

            return((DataTemplate)XamlReader.Parse(xaml, context));
        }
        protected DataTemplate GetGroupValueTemplate()
        {
            string xamlDataTemplate = "<DataTemplate>";

            xamlDataTemplate += "<self:GroupCheckBox Content=\"{Binding Value}\" Margin=\"8,0,0,0\"  CheckStates=\"{Binding Path=RowData.RowState.(self:CheckableGroupBehavior.CheckList), Mode=TwoWay}\"/>";
            xamlDataTemplate += "</DataTemplate>";
            ParserContext context = new ParserContext();

            context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
            context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
            context.XmlnsDictionary.Add("self", "clr-namespace:DevExpress.Example03;assembly=DevExpress.Example03");
            DataTemplate template = (DataTemplate)XamlReader.Parse(xamlDataTemplate, context);

            return(template);
        }
コード例 #15
0
        public LayoutTreeHelperTests()
        {
            textBoxTemplate = (DataTemplate)XamlReader.Parse(
                @"
<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" 
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<TextBox/>
</DataTemplate>");

            textBlockTemplate = (DataTemplate)XamlReader.Parse(
                @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" 
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<TextBlock><Run>Text</Run></TextBlock>
</DataTemplate>");
        }
コード例 #16
0
        private IEnumerable GetStatTemplate(string statTemplateKey)
        {
            var resources = (ResourceDictionary)XamlReader.Parse(_resourceElementString);

            if (resources.Contains(statTemplateKey))
            {
                var template = (IEnumerable)resources[statTemplateKey];
                return(template);
            }
            else
            {
                this.LogError("invalid stat template");
                return(new object[0]);
            }
        }
コード例 #17
0
        /// <summary>
        /// Converts from XAML markup to a WPF FlowDocument.
        /// </summary>
        public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            /* See http://stackoverflow.com/questions/897505/getting-a-flowdocument-from-a-xaml-template-file */

            var flowDocument = new FlowDocument();

            if (value != null)
            {
                var xamlText = (string)value;
                flowDocument = (FlowDocument)XamlReader.Parse(xamlText);
            }

            // Set return value
            return(flowDocument);
        }
コード例 #18
0
        public MainWindow()
        {
            InitializeComponent();

            var compiledTextBlock = Content as TextBlock;

            var dynamicSelfClosing = (TextBlock)XamlReader.Parse("<TextBlock xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xml:space='preserve'> <Run/> </TextBlock>");
            var dynamicCosing      = (TextBlock)XamlReader.Parse("<TextBlock xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xml:space='preserve'> <Run></Run> </TextBlock>");

            MessageBox.Show(
                $"Compiled: {compiledTextBlock.Inlines.Count}\n" +
                $"Dynamic Self-Closing: {dynamicSelfClosing.Inlines.Count}\n" +
                $"Dynamic Normally Closing:{dynamicCosing.Inlines.Count}");
            Close();
        }
コード例 #19
0
        private void ButtonImport_Click(object sender, RoutedEventArgs e)
        {
            Map map = null;

            using (FileStream fs = new FileStream("D:/Map1.txt", FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                map = (Map)formatter.Deserialize(fs);
            }
            if (map != null)
            {
                Canvas canvas = (Canvas)XamlReader.Parse(map.MapGraph);
                mainCanvas.Children.Add(canvas);
            }
        }
コード例 #20
0
        public static ProjectDefinition Load(XElement root)
        {
            XNamespace is3  = "clr-namespace:IS3.Core;assembly=IS3.Core";
            XElement   node = root.Element(is3 + "ProjectDefinition");
            object     obj  = null;

            if (node != null)
            {
                obj = XamlReader.Parse(node.ToString());
            }

            ProjectDefinition prjDef = (ProjectDefinition)obj;

            return((ProjectDefinition)obj);
        }
コード例 #21
0
        /// <summary>
        /// Creates the <see cref="DataTemplate"/> with the root node of the specified type.
        /// </summary>
        /// <param name="rootType">The type of the root node of the <see cref="DataTemplate"/> to create.</param>
        /// <returns>The <see cref="DataTemplate"/> with the root node of the <paramref name="rootType"/>.</returns>
        internal static DataTemplate CreateTemplate(Type rootType)
        {
            ParserContext context = new ParserContext();

            XamlTypeMapper mapper = new XamlTypeMapper(Array.Empty <string>());

            mapper.AddMappingProcessingInstruction(XmlNamespace, rootType.Namespace, rootType.Assembly.FullName);

            context.XamlTypeMapper = mapper;

            context.XmlnsDictionary.Add(string.Empty, NamespaceURI);
            context.XmlnsDictionary.Add(XmlNamespace, XmlNamespace);

            return(XamlReader.Parse(string.Format(Template, rootType.Name), context) as DataTemplate);
        }
コード例 #22
0
        public static T CloneControl <T>(T control) where T : Control, new()
        {
            //string xaml = System.Windows.Markup.XamlWriter.Save(control);
            //T rtb2 = System.Windows.Markup.XamlReader.Parse(xaml) as T;
            //return rtb2;
            string       rectXaml     = XamlWriter.Save(control);
            StringReader stringReader = new StringReader(rectXaml);

            //XmlReader xmlReader = XmlReader.Create(stringReader);
            //T clonedChild = (T)XamlReader.Load(xmlReader);

            var xamlReader = XamlReader.Parse(rectXaml) as T;

            return(xamlReader);
        }
コード例 #23
0
        private Geometry PathMarkupToGeometry(string pathMarkup)
        {
            string xaml = "<Path " +
                          "xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>" +
                          "<Path.Data>" + pathMarkup + "</Path.Data></Path>";

            // Load を Parseへ
            Path path = XamlReader.Parse(xaml) as Path;

            // Detach the PathGeometry from the Path
            Geometry geometry = path.Data;

            path.Data = null;
            return(geometry);
        }
コード例 #24
0
 private void OnSetXamlClick(object sender, RoutedEventArgs e)
 {
     try
     {
         _rtb.Document.Blocks.Clear();
         FlowDocument doc = (FlowDocument)XamlReader.Parse(_txtXaml.Text);
         AddDocument(doc, _rtb.Document);
         _tabText.SelectedItem = _tbiRtf;
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.ToString());
         MessageBox.Show(ex.Message);
     }
 }
コード例 #25
0
ファイル: ShapeBuilder.cs プロジェクト: BoltBait/CodeLab
        private static Geometry TryParseGeometry(string geometryText)
        {
            Geometry geometry = null;

            try
            {
                geometry = (Geometry)XamlReader.Parse(geometryText);
            }
            catch (XamlParseException ex)
            {
                error = Error.NewShapeError(ex.LineNumber, ex.LinePosition, ex.Message);
            }

            return(geometry);
        }
コード例 #26
0
        private void showNote()
        {
            StickyNote note = new StickyNote()
            {
                DataContext = this
            };

            note.txt_noteContent.Document =
                XamlReader.Parse(
                    HtmlToXamlConverter.ConvertHtmlToXaml(this.pageContent, true)
                    ) as FlowDocument;

            note.ShowInTaskbar = false;
            note.Show();
        }
コード例 #27
0
 private ControlTemplate GetTemplate()
 {
     Debug.WriteLine("GetTemplate");
     return((ControlTemplate)XamlReader.Parse(@"
 <ControlTemplate  xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
                   xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
     <Border BorderBrush=""Black"" BorderThickness=""0"" CornerRadius=""1"">
         <StackPanel Orientation=""Horizontal"" VerticalAlignment=""Center"" HorizontalAlignment=""Left"" Background=""White"">
             <CheckBox Name=""checkBox"" VerticalAlignment=""Center"" />
             <TextBox Name=""textBox"" BorderThickness=""0""/>
             <TextBlock Name=""textBlock"" Text=""▼""/>
         </StackPanel>
     </Border>
 </ControlTemplate>"));
 }
コード例 #28
0
        private void tryLoadChildFromServer()
        {
            var req = new XMLHttpRequest();

            req.OnReadyStateChange = () =>
            {
                if (req.ReadyState == AjaxReadyState.Done && req.Status == 200)
                {
                    var loader = new XamlReader();
                    this.child = loader.Parse(req.ResponseText);
                }
            };
            req.Open("GET", this.typename.Replace(".", "/") + ".xml", true);
            req.Send();
        }
コード例 #29
0
        private void RefreshXamlCommand_Execute(object sender, ExecutedRoutedEventArgs e)
        {
            var xamlFile = this.XamlFile;

            if (!string.IsNullOrEmpty(xamlFile) && File.Exists(xamlFile))
            {
                var xaml = File.ReadAllText(xamlFile);
                var dic  = XamlReader.Parse(xaml) as ResourceDictionary;
                Application.Current.Resources.MergedDictionaries.Add(dic);

                this.RefreshControl();

                App.Current.Status = "界面刷新完成。".Translate() + DateTime.Now;
            }
        }
コード例 #30
0
        /// <summary>
        /// Crée le DataTemplate permettant d'afficher l'entête de la colonne.
        /// </summary>
        /// <param name="labelBindingPath">le chemin vers le libellé.</param>
        /// <returns>Le DataTemplate.</returns>
        private static DataTemplate CreateHeaderTemplate(string labelBindingPath)
        {
            var context = new ParserContext();

            context.XamlTypeMapper = new XamlTypeMapper(new string[0]);

            context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
            context.XmlnsDictionary.Add("k", "http://schemas.kprocess.com/xaml/framework");

            var templateString = string.Format(HeaderTemplateFormat, labelBindingPath);

            var template = (DataTemplate)XamlReader.Parse(templateString, context);

            return(template);
        }