public static void SerializeContentTo([NotNull] this ContentControl control, [NotNull] Stream stream) => XamlWriter.Save(control.Content, stream);
public static T DeepCopy <T>(this T element) { return((T)XamlReader.Load(new XmlTextReader(new StringReader(XamlWriter.Save(element))))); }
public static string RoundtripXaml(string xaml) { return(XamlWriter.Save(XamlReader.Parse(xaml))); }
private bool ConvertDocument(string filePath = null) { if (string.IsNullOrWhiteSpace(filePath) || File.Exists(filePath) == false) { filePath = _svgFilePath; } try { if (string.IsNullOrWhiteSpace(filePath) || File.Exists(filePath) == false) { return(false); } //DrawingGroup drawing = _fileReader.Read(filePath, _directoryInfo); //if (drawing == null) //{ // return false; //} //if (_xamlPage != null && !string.IsNullOrWhiteSpace(_xamlFilePath)) //{ // if (File.Exists(_xamlFilePath)) // { // _xamlPage.LoadDocument(_xamlFilePath); // // Delete the file after loading it... // File.Delete(_xamlFilePath); // } // else // { // string xamlFilePath = IoPath.Combine(_directoryInfo.FullName, // IoPath.GetFileNameWithoutExtension(filePath) + ".xaml"); // if (File.Exists(xamlFilePath)) // { // _xamlPage.LoadDocument(xamlFilePath); // // Delete the file after loading it... // File.Delete(xamlFilePath); // } // } //} //_currentDrawing = drawing; //Rect drawingBounds = drawing.Bounds; svgDrawing.UnloadDiagrams(); string xamlFilePath = IoPath.Combine(_directoryInfo.FullName, IoPath.GetFileNameWithoutExtension(filePath) + ".xaml"); //svgDrawing.RenderDiagrams(drawing); if (svgDrawing.RenderDiagrams(filePath)) { if (_xamlPage != null) { //using (MemoryStream stream = new MemoryStream()) using (FileStream stream = File.Create(xamlFilePath)) { XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.Indent = true; writerSettings.OmitXmlDeclaration = true; writerSettings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(stream, writerSettings)) { XamlWriter.Save(svgDrawing.Drawing, writer); } //using (XmlWriter writer = XmlWriter.Create(stream, writerSettings)) //{ // try // { // XmlXamlWriter xamlWriter = new XmlXamlWriter(); // xamlWriter.Save(svgDrawing.Drawing, writer); // } // catch (Exception) // { // stream.Flush(); // throw; // } //} if (stream.Length > 0) { stream.Position = 0; } _xamlPage.LoadDocument(stream); } } } zoomPanControl.InvalidateMeasure(); Rect bounds = svgDrawing.Bounds; //zoomPanControl.AnimatedScaleToFit(); //Rect rect = new Rect(0, 0, // mainFrame.RenderSize.Width, mainFrame.RenderSize.Height); //Rect rect = new Rect(0, 0, // bounds.Width, bounds.Height); if (bounds.IsEmpty) { bounds = new Rect(0, 0, viewerFrame.ActualWidth, viewerFrame.ActualHeight); } zoomPanControl.AnimatedZoomTo(bounds); return(true); } catch (Exception ex) { //svgDrawing.Source = null; svgDrawing.UnloadDiagrams(); this.ReportError(ex); return(false); } }
/// <summary> /// Add new translation row (a panel with respective elements) to the dialog. /// </summary> private void AddTranslationRow(Translation tr) { var copy = (FrameworkElement)XamlReader.Parse(XamlWriter.Save(translationRow)); int addButtonIdx = translationsPanel.Children.IndexOf(addTranslationBtn); copy.Name = null; //To show that it's a new item copy.Visibility = Visibility.Visible; copy.Tag = tr; var newTranslationLbl = (TextBlock)copy.FindName(nameof(translationLbl)); newTranslationLbl.Text = TranslationConverter.ConvertToString(tr); newTranslationLbl.MouseUp += (s, e) => { //Edit the translation var dlg = new TranslationsEditDlg(tr.Text, tr.Part) { Owner = this }; if (dlg.ShowDialog() == true) { tr.Text = dlg.Translation.Value.translation; tr.Part = dlg.Translation.Value.partOfSpeech; newTranslationLbl.Text = TranslationConverter.ConvertToString(tr); ChangesHaveBeenMade(); } }; var newRemoveBtn = (Button)copy.FindName(nameof(trRemoveBtn)); newRemoveBtn.Click += (s, e) => { //Remove the translation LooseHeight(); translationsPanel.Children.Remove(copy); translations.Remove(tr); FixHeight(); countOfShownTranslations--; UpdateAddButtonState(); UpdateTranslationsArrowsState(); ChangesHaveBeenMade(); }; var newTrUpBtn = (Button)copy.FindName(nameof(trUpBtn)); newTrUpBtn.Click += (s, e) => MoveTranslationRow(copy, moveUp: true); var newTrDownBtn = (Button)copy.FindName(nameof(trDownBtn)); newTrDownBtn.Click += (s, e) => MoveTranslationRow(copy, moveUp: false); LooseHeight(); translationsPanel.Children.Insert(addButtonIdx, copy); if (Visibility == Visibility.Visible) //Only if form is already shown and knows its size { FixHeight(); } countOfShownTranslations++; UpdateAddButtonState(); }
private string XamlConvert(Border image) { return(XamlWriter.Save(image)); }
/// <summary> /// Create a XamlPropertyValue for the specified value instance. /// </summary> public XamlPropertyValue CreatePropertyValue(object instance, XamlProperty forProperty) { if (instance == null) { throw new ArgumentNullException("instance"); } Type elementType = instance.GetType(); TypeConverter c = TypeDescriptor.GetConverter(instance); var ctx = new DummyTypeDescriptorContext(this.ServiceProvider); ctx.Instance = instance; bool hasStringConverter = c.CanConvertTo(ctx, typeof(string)) && c.CanConvertFrom(typeof(string)); if (forProperty != null && hasStringConverter) { if (instance is SolidColorBrush && _colorBrushDictionary.ContainsKey(((SolidColorBrush)instance).Color)) { var name = _colorBrushDictionary[((SolidColorBrush)instance).Color]; return(new XamlTextValue(this, name)); } return(new XamlTextValue(this, c.ConvertToInvariantString(ctx, instance))); } string ns = GetNamespaceFor(elementType); string prefix = GetPrefixForNamespace(ns); XmlElement xml = _xmlDoc.CreateElement(prefix, elementType.Name, ns); if (hasStringConverter && (XamlObject.GetContentPropertyName(elementType) != null || IsNativeType(instance))) { xml.InnerText = c.ConvertToInvariantString(instance); } else if (instance is Brush && forProperty != null) // TODO: this is a hacky fix, because Brush Editor doesn't // edit Design Items and so we have no XML, only the Brush // object and we need to parse the Brush to XAML! { var s = new MemoryStream(); XamlWriter.Save(instance, s); s.Seek(0, SeekOrigin.Begin); XmlDocument doc = new XmlDocument(); doc.Load(s); xml = (XmlElement)_xmlDoc.ImportNode(doc.DocumentElement, true); var attLst = xml.Attributes.Cast <XmlAttribute>().ToList(); foreach (XmlAttribute att in attLst) { if (att.Name.StartsWith(XamlConstants.Xmlns)) { var rootAtt = doc.DocumentElement.GetAttributeNode(att.Name); if (rootAtt != null && rootAtt.Value == att.Value) { xml.Attributes.Remove(att); } } } } return(new XamlObject(this, xml, elementType, instance)); }
public static T Duplicate <T>(this T reference) where T : FrameworkElement { return(XamlReader.Parse(XamlWriter.Save(reference)) as T); }
/// <summary> /// Serializes <code>obj</code> into a XAML string /// </summary> /// <param name="obj">Object to serialize</param> /// <returns>Serialized XAML version of <code>obj</code></returns> public static string SerializeObject(object obj) { return(XamlWriter.Save(obj)); }
public virtual string ToCtrb() { return($"{XamlWriter.Save(Element)}"); }
protected override void OnPreviewMouseUp(MouseButtonEventArgs e) { string xamlString; base.OnPreviewMouseUp(e); if (IsDown == false) { return; } IsDown = false; if (!(this.Parent is Toolbox) && !(this.Parent is WrapPanel)) { return; } switch (this.AssetType) { case jg.Editor.Library.AssetType.Text: xamlString = "Text"; break; case jg.Editor.Library.AssetType.Topic: xamlString = "Topic"; break; case jg.Editor.Library.AssetType.TopicDrag: xamlString = "TopicDrag"; break; case jg.Editor.Library.AssetType.Image: xamlString = "Image"; break; case jg.Editor.Library.AssetType.Movie: xamlString = "Movie"; break; case jg.Editor.Library.AssetType.TextGrid: xamlString = "TextGrid"; break; case jg.Editor.Library.AssetType.Sound: xamlString = "Sound"; break; case Editor.Library.AssetType.Document: xamlString = "Document"; break; case Editor.Library.AssetType.Message: xamlString = "Message"; break; case Editor.Library.AssetType.Line: xamlString = "Line"; break; case Editor.Library.AssetType.HTML5: xamlString = "HTML5"; break; case Editor.Library.AssetType.TPageGroup: xamlString = "TPageGroup"; break; default: xamlString = XamlWriter.Save(this); break; } if (AddAsset != null) { AddAsset(xamlString); } }
public FileChoice() { InitializeComponent(); listOfFiles = (from a in Directory.GetFiles(Directory.GetCurrentDirectory().ToString(), "*.dat") select System.IO.Path.GetFileName(a)).ToList(); if (listOfFiles.Count == 0) { var noFiles = new Label { Style = this.Resources["LabelStyle"] as Style, Content = "У вас нет сохранённых симуляций", Width = 494, HorizontalContentAlignment = HorizontalAlignment.Center }; ListOfFiles.Children.Add(noFiles); } else { for (int i = 0; i < listOfFiles.Count; i++) { var fileLine = new StackPanel { MinHeight = 70, Orientation = Orientation.Horizontal }; var fileName = new TextBlock { Width = 300, Style = this.Resources["TextBlockStyle"] as Style, Text = listOfFiles[i].Substring(0, listOfFiles[i].Length - 4), VerticalAlignment = VerticalAlignment.Center, TextWrapping = TextWrapping.Wrap }; fileLine.Children.Add(fileName); var EmptySpace = new Label { Width = 55 }; fileLine.Children.Add(EmptySpace); string template = XamlWriter.Save(LoadTemplate.Template); StringReader stringReader = new StringReader(template); XmlReader xmlReader = XmlReader.Create(stringReader); var okButton = new Button { Name = "File" + i.ToString(), Height = 50, Width = 50, VerticalAlignment = VerticalAlignment.Center, Template = (ControlTemplate)XamlReader.Load(xmlReader) }; okButton.Click += OkButton_Click; fileLine.Children.Add(okButton); var EmptySpace2 = new Label { Width = 10 }; fileLine.Children.Add(EmptySpace2); string template2 = XamlWriter.Save(DeleteTemplate.Template); StringReader stringReader2 = new StringReader(template2); XmlReader xmlReader2 = XmlReader.Create(stringReader2); var deleteButton = new Button { Name = "File" + i.ToString(), Template = (ControlTemplate)XamlReader.Load(xmlReader2), Height = 50, Width = 50, VerticalAlignment = VerticalAlignment.Center }; deleteButton.Click += DeleteButton_Click; fileLine.Children.Add(deleteButton); ListOfFiles.Children.Add(fileLine); } } }
private static void ConvertToXml <T>(string name, XContainer xRoot, T value) { xRoot.Add(new XElement(name, XamlWriter.Save(value))); }
public static string ConvertRtfToHtml(FlowDocument doc) { var xamlText = XamlWriter.Save(doc); return(XamlToHtmlConverter.ConvertXamlToHtml(xamlText, false)); }
/// <summary> /// Fills document with data /// </summary> /// <exception cref="InvalidDataException">ReportTableRow must have a TableRowGroup as parent</exception> protected virtual void FillData() { ArrayList blockDocumentValues = _dynamicCache.GetFlowDocumentVisualListByInterface(typeof(IInlineDocumentValue)); // walker.Walk<IInlineDocumentValue>(_flowDocument); ArrayList blockTableRows = _dynamicCache.GetFlowDocumentVisualListByInterface(typeof(ITableRowForDataTable)); // walker.Walk<TableRowForDataTable>(_flowDocument); ArrayList blockAggregateValues = _dynamicCache.GetFlowDocumentVisualListByType(typeof(InlineAggregateValue)); // walker.Walk<InlineAggregateValue>(_flowDocument); ArrayList charts = _dynamicCache.GetFlowDocumentVisualListByInterface(typeof(IChart)); // walker.Walk<IChart>(_flowDocument); ArrayList dynamicHeaderTableRows = _dynamicCache.GetFlowDocumentVisualListByInterface(typeof(ITableRowForDynamicHeader)); ArrayList dynamicDataTableRows = _dynamicCache.GetFlowDocumentVisualListByInterface(typeof(ITableRowForDynamicDataTable)); ArrayList documentConditions = _dynamicCache.GetFlowDocumentVisualListByInterface(typeof(IDocumentCondition)); List <Block> blocks = new List <Block>(); if (_blockPageHeader != null) { blocks.Add(_blockPageHeader); } if (_blockPageFooter != null) { blocks.Add(_blockPageFooter); } DocumentWalker walker = new DocumentWalker(); blockDocumentValues.AddRange(walker.TraverseBlockCollection <IInlineDocumentValue>(blocks)); Dictionary <string, List <object> > aggregateValues = new Dictionary <string, List <object> >(); FillCharts(charts); // hide conditional text blocks foreach (IDocumentCondition dc in documentConditions) { if (dc == null) { continue; } dc.PerformRenderUpdate(_data); } // fill report values foreach (IInlineDocumentValue dv in blockDocumentValues) { if (dv == null) { continue; } object obj; if ((dv.PropertyName != null) && (_data.ReportDocumentValues.TryGetValue(dv.PropertyName, out obj))) { dv.Value = obj; RememberAggregateValue(aggregateValues, dv.AggregateGroup, obj); } else { if ((_data.ShowUnknownValues) && (dv.Value == null)) { dv.Value = "[" + ((dv.PropertyName != null) ? dv.PropertyName : "NULL") + "]"; } RememberAggregateValue(aggregateValues, dv.AggregateGroup, null); } } // fill dynamic tables foreach (ITableRowForDynamicDataTable iTableRow in dynamicDataTableRows) { TableRow tableRow = iTableRow as TableRow; if (tableRow == null) { continue; } TableRowGroup tableGroup = tableRow.Parent as TableRowGroup; if (tableGroup == null) { continue; } TableRow currentRow; DataTable table = _data.GetDataTableByName(iTableRow.TableName); for (int i = 0; i < table.Rows.Count; i++) { currentRow = new TableRow(); DataRow dataRow = table.Rows[i]; for (int j = 0; j < table.Columns.Count; j++) { string value = dataRow[j].ToString(); currentRow.Cells.Add(new TableCell(new Paragraph(new Run(value)))); } tableGroup.Rows.Add(currentRow); } } foreach (ITableRowForDynamicHeader iTableRow in dynamicHeaderTableRows) { TableRow tableRow = iTableRow as TableRow; if (tableRow == null) { continue; } DataTable table = _data.GetDataTableByName(iTableRow.TableName); foreach (DataRow row in table.Rows) { string value = row[0].ToString(); TableCell tableCell = new TableCell(new Paragraph(new Run(value))); tableRow.Cells.Add(tableCell); } } // group table row groups Dictionary <TableRowGroup, List <TableRow> > groupedRows = new Dictionary <TableRowGroup, List <TableRow> >(); Dictionary <TableRowGroup, string> tableNames = new Dictionary <TableRowGroup, string>(); foreach (TableRow tableRow in blockTableRows) { TableRowGroup rowGroup = tableRow.Parent as TableRowGroup; if (rowGroup == null) { continue; } ITableRowForDataTable iTableRow = tableRow as ITableRowForDataTable; if ((iTableRow != null) && (iTableRow.TableName != null)) { string tableName; if (tableNames.TryGetValue(rowGroup, out tableName)) { if (tableName != iTableRow.TableName.Trim().ToLowerInvariant()) { throw new ReportingException("TableRowGroup cannot be mapped to different DataTables in TableRowForDataTable"); } } else { tableNames[rowGroup] = iTableRow.TableName.Trim().ToLowerInvariant(); } } List <TableRow> rows; if (!groupedRows.TryGetValue(rowGroup, out rows)) { rows = new List <TableRow>(); groupedRows[rowGroup] = rows; } rows.Add(tableRow); } // fill tables foreach (KeyValuePair <TableRowGroup, List <TableRow> > groupedRow in groupedRows) { TableRowGroup rowGroup = groupedRow.Key; ITableRowForDataTable iTableRow = groupedRow.Value[0] as ITableRowForDataTable; if (iTableRow == null) { continue; } DataTable table = _data.GetDataTableByName(iTableRow.TableName); if (table == null) { if (_data.ShowUnknownValues) { // show unknown values foreach (TableRow tableRow in groupedRow.Value) { foreach (TableCell cell in tableRow.Cells) { DocumentWalker localWalker = new DocumentWalker(); List <ITableCellValue> tableCells = localWalker.TraverseBlockCollection <ITableCellValue>(cell.Blocks); foreach (ITableCellValue cv in tableCells) { IPropertyValue dv = cv as IPropertyValue; if (dv == null) { continue; } dv.Value = "[" + dv.PropertyName + "]"; RememberAggregateValue(aggregateValues, cv.AggregateGroup, null); } } } } else { continue; } } else { List <TableRow> listNewRows = new List <TableRow>(); TableRow newTableRow; // clone XAML rows List <string> clonedRows = new List <string>(); foreach (TableRow row in rowGroup.Rows) { TableRowForDataTable reportTableRow = row as TableRowForDataTable; if (reportTableRow == null) { clonedRows.Add(null); } clonedRows.Add(XamlWriter.Save(reportTableRow)); } for (int i = 0; i < table.Rows.Count; i++) { DataRow dataRow = table.Rows[i]; for (int j = 0; j < rowGroup.Rows.Count; j++) { TableRow row = rowGroup.Rows[j]; TableRowForDataTable reportTableRow = row as TableRowForDataTable; if (reportTableRow == null) { // clone regular row listNewRows.Add(XamlHelper.CloneTableRow(row)); } else { // clone ReportTableRows newTableRow = (TableRow)XamlHelper.LoadXamlFromString(clonedRows[j]); foreach (TableCell cell in newTableRow.Cells) { DocumentWalker localWalker = new DocumentWalker(); List <ITableCellValue> newCells = localWalker.TraverseBlockCollection <ITableCellValue>(cell.Blocks); foreach (ITableCellValue cv in newCells) { IPropertyValue dv = cv as IPropertyValue; if (dv == null) { continue; } try { object obj = dataRow[dv.PropertyName]; if (obj == DBNull.Value) { obj = null; } dv.Value = obj; RememberAggregateValue(aggregateValues, cv.AggregateGroup, obj); } catch { if (_data.ShowUnknownValues) { dv.Value = "[" + dv.PropertyName + "]"; } else { dv.Value = ""; } RememberAggregateValue(aggregateValues, cv.AggregateGroup, null); } } } listNewRows.Add(newTableRow); // fire event _report.FireEventDataRowBoundEventArgs(new DataRowBoundEventArgs(_report, dataRow) { TableName = dataRow.Table.TableName, TableRow = newTableRow }); } } } rowGroup.Rows.Clear(); foreach (TableRow row in listNewRows) { rowGroup.Rows.Add(row); } } } // fill aggregate values foreach (InlineAggregateValue av in blockAggregateValues) { if (String.IsNullOrEmpty(av.AggregateGroup)) { continue; } string[] aggregateGroups = av.AggregateGroup.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (var group in aggregateGroups) { if (!aggregateValues.ContainsKey(group)) { av.Text = av.EmptyValue; break; } } av.Text = av.ComputeAndFormat(aggregateValues); } }
private static void SaveInlineNote(XmlWriter wr, OutlinerNote outlinerNote) { wr.WriteStartElement("InlineNote"); wr.WriteRaw(XamlWriter.Save(outlinerNote.InlineNoteDocument)); wr.WriteEndElement(); }
protected override void OnExecute(object param) { System.Windows.Forms.DialogResult dresult = System.Windows.Forms.MessageBox.Show( BSky.GlobalResources.Properties.Resources.RestartToApplyChanges + BSky.GlobalResources.Properties.Resources.ConfirmDialogInstall, BSky.GlobalResources.Properties.Resources.InstallNewDialog, System.Windows.Forms.MessageBoxButtons.YesNoCancel, System.Windows.Forms.MessageBoxIcon.Question); if (dresult == System.Windows.Forms.DialogResult.Yes)//save { IUnityContainer container = LifetimeService.Instance.Container; IDataService service = container.Resolve <IDataService>(); IUIController controller = container.Resolve <IUIController>(); IDashBoardService dashboardService = container.Resolve <IDashBoardService>(); Window1 mainWin = container.Resolve <Window1>();//15Jan2013 extractedfiles = new List <string>(); OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = FileNameFilter; bool?output = openFileDialog.ShowDialog(Application.Current.MainWindow); if (output.HasValue && output.Value) { FileStream fileStreamIn = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read); ZipInputStream zipInStream = new ZipInputStream(fileStreamIn); string xamlFile = string.Empty, outputFile = string.Empty; ZipEntry entry = zipInStream.GetNextEntry(); string tempDir = Path.GetTempPath(); //Extract the files while (entry != null) { //if(System.IO.File.Exists((@".\config\" + entry.Name))) //{ // if(MessageBox.Show("Do you want to replace existing file?","Warning",MessageBoxButton.YesNo,MessageBoxImage.Hand) == MessageBoxResult.No) // continue; //} FileStream fileStreamOut = new FileStream(Path.Combine(tempDir, entry.Name), FileMode.Create, FileAccess.Write); if (entry.Name.EndsWith(".xaml")) { xamlFile = entry.Name; } if (entry.Name.EndsWith(".xml")) { outputFile = entry.Name; } int size; byte[] buffer = new byte[1024]; do { size = zipInStream.Read(buffer, 0, buffer.Length); fileStreamOut.Write(buffer, 0, size); } while (size > 0); fileStreamOut.Close(); entry = zipInStream.GetNextEntry(); MessageBox.Show("Extracted:" + entry.Name + " in " + tempDir); //adding fullpath filename to list //08May2015 extractedfiles.Add(Path.Combine(tempDir, entry.Name)); } zipInStream.Close(); fileStreamIn.Close(); if (string.IsNullOrEmpty(outputFile)) { MessageBox.Show(BSky.GlobalResources.Properties.Resources.CantInstallDialogNoOutFile); return; } //Load the dialog object, check the location and modify menu file. if (!string.IsNullOrEmpty(xamlFile) && !string.IsNullOrEmpty(outputFile)) { FileStream stream = System.IO.File.Open(Path.Combine(tempDir, xamlFile), FileMode.Open); try { object obj = XamlReader.Load(stream); BSky.Controls.BSkyCanvas canvas = obj as BSky.Controls.BSkyCanvas; string menulocation = canvas.MenuLocation; string title = canvas.Title; if (string.IsNullOrEmpty(canvas.Title)) { title = Microsoft.VisualBasic.Interaction.InputBox("Get Item Name", "Item Name", "New Node"); if (!string.IsNullOrEmpty(title)) { MessageBox.Show(BSky.GlobalResources.Properties.Resources.CantInstallDialogNoTitle, BSky.GlobalResources.Properties.Resources.DialogTitleEmpty); return; } } //23Apr2015 bool? result = dashboardService.SetElementLocaton(menulocation, title, Path.Combine(@".\config\", xamlFile), false, ""); bool? result = dashboardService.SetElementLocaton(menulocation, title, Path.Combine(string.Format(@"{0}", BSkyAppData.RoamingUserBSkyConfigL18nPath), xamlFile), false, "");//23Apr2015 MessageBoxResult msgResult = MessageBoxResult.No; if (result.HasValue && !result.Value) { msgResult = MessageBox.Show(BSky.GlobalResources.Properties.Resources.ConfirmDialogOverwrite, BSky.GlobalResources.Properties.Resources.WarnOverwrite, MessageBoxButton.YesNo); } if (result.HasValue && (result.Value || msgResult == MessageBoxResult.Yes)) { //23Apr2015 canvas.OutputDefinition = Path.GetFullPath(@".\Config\" + outputFile); canvas.OutputDefinition = Path.GetFullPath(string.Format(@"{0}", BSkyAppData.RoamingUserBSkyConfigL18nPath) + outputFile);//23Apr2015 System.IO.File.Copy(Path.Combine(tempDir, outputFile), canvas.OutputDefinition, true); string xaml = XamlWriter.Save(canvas); //23Apr2015 FileStream outputstream = System.IO.File.Create(@".\Config\" + xamlFile); FileStream outputstream = System.IO.File.Create(string.Format(@"{0}", BSkyAppData.RoamingUserBSkyConfigL18nPath) + xamlFile);//23Apr2015 TextWriter writer = new StreamWriter(outputstream); writer.Write(xaml); writer.Close(); MessageBox.Show(BSky.GlobalResources.Properties.Resources.RestartToApplyChanges2, BSky.GlobalResources.Properties.Resources.DialogInstalled); } else { string sInput = "New Command Node"; string aboveBelowSibling = "Below";//position of new command based on sibling location. Enum can be used for Above/Below string location = dashboardService.SelectLocation(ref sInput, ref aboveBelowSibling); //sInput is prefixed to XAML and XML filenames. You can think of dropping it for prefixing //string sInput = Microsoft.VisualBasic.Interaction.InputBox("Get Item Name", "Item Name", "Command Name"); if (!string.IsNullOrEmpty(location)) { //string sInputNoBlanks = sInput.Replace(' ','_');//26sep2012 //23Apr2015 dashboardService.SetElementLocaton(location, sInput, Path.Combine(@".\Config\", sInput + xamlFile), true, aboveBelowSibling); dashboardService.SetElementLocaton(location, sInput, Path.Combine(string.Format(@"{0}", BSkyAppData.RoamingUserBSkyConfigL18nPath), sInput + xamlFile), true, aboveBelowSibling);//23Apr2015 ///12Oct2012 canvas.OutputDefinition = Path.GetFullPath(@".\config\" + sInput + outputFile);///output template filename will be same as in zip //23Apr2015 canvas.OutputDefinition = Path.GetFullPath(@".\Config\" + sInput + xamlFile.Replace("xaml", "xml"));///output template filename will be same as dialog filename. No matter whats in zip file. canvas.OutputDefinition = Path.GetFullPath(string.Format(@"{0}", BSkyAppData.RoamingUserBSkyConfigL18nPath) + sInput + xamlFile.Replace("xaml", "xml"));//23Apr2015 //output template filename will be same as dialog filename. No matter whats in zip file. System.IO.File.Copy(Path.Combine(tempDir, outputFile), canvas.OutputDefinition, true); ///Following commented lines should not execute 17Jan2013 ///These are writing a xaml and putting datatemplate tag in XAML while installing. //string xaml = XamlWriter.Save(canvas); //FileStream outputstream = System.IO.File.Create(@".\Config\" + sInput + xamlFile); //TextWriter writer = new StreamWriter(outputstream); //writer.Write(xaml); //writer.Close(); //23Apr2015 string installpath = Path.GetFullPath(@".\Config\" + sInput + xamlFile); string installpath = Path.GetFullPath(string.Format(@"{0}", BSkyAppData.RoamingUserBSkyConfigL18nPath) + sInput + xamlFile);//23Apr2015 System.IO.File.Copy(Path.Combine(tempDir, xamlFile), installpath, true); MessageBox.Show(BSky.GlobalResources.Properties.Resources.RestartToApplyChanges2, BSky.GlobalResources.Properties.Resources.DialogInstalled); mainWin.Window_Refresh_Menus();//15Jan2013 } } CleanTempFiles(); } catch (Exception e) { MessageBox.Show(BSky.GlobalResources.Properties.Resources.CantInstallDialog, BSky.GlobalResources.Properties.Resources.InstallFailed); logService.WriteToLogLevel("Couldn't install Dialog", LogLevelEnum.Error); } } } } }
/// <summary> /// This sets the source SVG for a <see cref="SvgCanvas"/> by using the supplied Uniform Resource Identifier (URI) /// and optionally processing the result asynchronously. /// </summary> /// <param name="uriSource">A reference to the SVG source file.</param> /// <param name="useAsync"> /// A value indicating whether to process the result asynchronously. The default value is <see langword="false"/>, /// the SVG conversion is processed synchronously. /// </param> /// <returns> /// A value that indicates whether the operation was successful. This is <see langword="true"/> /// if successful, otherwise, it is <see langword="false"/>. /// </returns> public bool Load(Uri uriSource, bool useAsync = false) { if (uriSource == null) { return(false); } var sourceUri = this.ResolveUri(uriSource); WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = _includeRuntime; settings.TextAsGeometry = _textAsGeometry; settings.OptimizePath = _optimizePath; if (_culture != null) { settings.CultureInfo = _culture; } try { if (useAsync) { MemoryStream drawingStream = new MemoryStream(); // Get the UI thread's context var context = TaskScheduler.FromCurrentSynchronizationContext(); Task.Factory.StartNew(() => { DrawingGroup drawing = this.CreateDrawing(sourceUri, settings); if (drawing != null) { _sourceUri = sourceUri; _sourceStream = null; XamlWriter.Save(drawing, drawingStream); drawingStream.Seek(0, SeekOrigin.Begin); } }).ContinueWith((t) => { if (drawingStream.Length != 0) { DrawingGroup drawing = (DrawingGroup)XamlReader.Load(drawingStream); this.OnLoadDrawing(drawing); } }, context); return(true); } else { DrawingGroup drawing = this.CreateDrawing(uriSource, settings); if (drawing != null) { _sourceUri = uriSource; _sourceStream = null; this.OnLoadDrawing(drawing); return(true); } } return(false); } catch { //TODO: Rethrow the exception? return(false); } }
private static void OnTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var me = (XamlView)d; var target = e.NewValue; var styles = me._styles; var tabs = me._tabs; if (target != null) { var tabsToRemove = new HashSet <string>(tabs.Select(o => o.Name)); foreach (var propertyInfo in target.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (!propertyInfo.CanRead || propertyInfo.GetIndexParameters().Length > 0) { continue; } if (AcceptableTypes.All(o => !o.IsAssignableFrom(propertyInfo.PropertyType))) { continue; } var propertyXaml = tabs.FirstOrDefault(o => o.Name == propertyInfo.Name); if (propertyXaml == null) { propertyXaml = new PropertyXaml(propertyInfo.Name); var insertIndex = tabs.Count; for (var i = 0; i < tabs.Count; i++) { if (string.CompareOrdinal(propertyInfo.Name, tabs[i].Name) < 0) { insertIndex = i; break; } } tabs.Insert(insertIndex, propertyXaml); } else { tabsToRemove.Remove(propertyInfo.Name); } var value = propertyInfo.GetValue(target, null); if (value != null) { try { string serializedStyle; using (var stringWriter = new StringWriter()) using (var xmlTextWriter = new XmlTextWriter(stringWriter) { Formatting = Formatting.Indented }) { XamlWriter.Save(value, xmlTextWriter); serializedStyle = stringWriter.ToString(); } var paragraph = new Paragraph { Style = styles.GeneralStyle }; paragraph.FillParagraph(serializedStyle, styles); propertyXaml.Document = new FlowDocument { Blocks = { paragraph } }; } catch (Exception ex) { var message = "[Exception]" + Environment.NewLine + Environment.NewLine + ex; var paragraph = new Paragraph { Style = styles.GeneralStyle }; paragraph.AddRun(message, styles.ErrorStyle); propertyXaml.Document = new FlowDocument { Blocks = { paragraph } }; } } else { var paragraph = new Paragraph { Style = styles.GeneralStyle }; paragraph.AddRun("(NULL)", styles.TextStyle); propertyXaml.Document = new FlowDocument { Blocks = { paragraph } }; } } foreach (var tabName in tabsToRemove) { var tab = tabs.FirstOrDefault(o => o.Name == tabName); if (tab != null) { tabs.Remove(tab); } } } else { tabs.Clear(); } }
/// <summary> /// This sets the source SVG for a <see cref="SvgCanvas"/> by accessing a stream /// and processing the result asynchronously. /// </summary> /// <param name="streamSource">The stream source that sets the SVG source value.</param> /// <param name="useCopyStream"> /// A value specifying whether to use a copy of the stream. The default is <see langword="true"/>, /// the SVG source stream is copied, rendered and stored. /// </param> /// <returns> /// A value that indicates whether the operation was successful. This is <see langword="true"/> /// if successful, otherwise, it is <see langword="false"/>. /// </returns> /// <remarks> /// The control will by default create a copy of the source stream to prevent any effect of disposing. /// If the source stream is stored, then use the <paramref name="useCopyStream"/> to prevent the control /// from creating its own copy. /// </remarks> public Task <bool> LoadAsync(Stream streamSource, bool useCopyStream = true) { TaskCompletionSource <bool> result = new TaskCompletionSource <bool>(); if (streamSource == null) { result.SetResult(false); return(result.Task); } WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = _includeRuntime; settings.TextAsGeometry = _textAsGeometry; settings.OptimizePath = _optimizePath; if (_culture != null) { settings.CultureInfo = _culture; } try { Stream svgStream = streamSource; if (useCopyStream) { svgStream = new MemoryStream(); // On dispose, the stream is close so copy it to the memory stream. streamSource.CopyTo(svgStream); //NOTE: Not working within the task scope // Move the position to the start of the stream svgStream.Seek(0, SeekOrigin.Begin); } else { if (svgStream.CanSeek && svgStream.Position != 0) { // Move the position to the start of the stream svgStream.Seek(0, SeekOrigin.Begin); } } _sourceUri = null; _sourceStream = svgStream; MemoryStream drawingStream = new MemoryStream(); // Get the UI thread's context var context = TaskScheduler.FromCurrentSynchronizationContext(); return(Task.Factory.StartNew <bool>(() => { DrawingGroup drawing = this.CreateDrawing(svgStream, settings); if (drawing != null) { XamlWriter.Save(drawing, drawingStream); drawingStream.Seek(0, SeekOrigin.Begin); return true; } return false; }).ContinueWith((t) => { if (t.Result && drawingStream.Length != 0) { DrawingGroup drawing = (DrawingGroup)XamlReader.Load(drawingStream); this.OnLoadDrawing(drawing); return true; } return false; }, context)); } catch (Exception ex) { result.SetResult(false); result.SetException(ex); return(result.Task); } }
/// <summary> /// Clone an element /// </summary> /// <param name="elementToClone"></param> /// <returns></returns> public static object CloneElement(object elementToClone) { string xaml = XamlWriter.Save(elementToClone); return(XamlReader.Load(new XmlTextReader(new StringReader(xaml)))); }
void UpdateDisplayTabs(object o, object o1) { Exception exception = null; try { if (o == MainTab && MainTab.SelectedItem == PanelTab) { TabControl.SelectedItem = TabCoreXaml; } TabItem selectedItem = TabControl.SelectedItem as TabItem; switch (selectedItem.Header.ToString()) { case "CoreXaml": TextRange range = new TextRange(CoreXaml.Document.ContentEnd, CoreXaml.Document.ContentStart); if (((TabItem)MainTab.SelectedItem).Header.ToString() == "RichTextBox") { XamlHelper.TextRange_SetXml(range, XamlHelper.ColoringXaml(XamlHelper.IndentXaml(XamlWriter.Save(MainEditor.Document)))); } else if (((TabItem)MainTab.SelectedItem).Header.ToString() == "Panel") { XamlHelper.TextRange_SetXml(range, XamlHelper.ColoringXaml(XamlHelper.IndentXaml(XamlWriter.Save(PanelTab.Content)))); } break; case "SelectionXaml": SelectionXaml.Text = XamlHelper.IndentXaml(XamlHelper.TextRange_GetXml(MainEditor.Selection)); break; case "TextSerializedXaml": TextSerializedXaml.Text = XamlHelper.IndentXaml(XamlHelper.TextRange_GetXml(new TextRange(MainEditor.Document.ContentEnd, MainEditor.Document.ContentStart))); break; case "DocumentTree": TreeViewhelper.SetupTreeView(TextTreeView, MainEditor.Document); break; default: OnError(new Exception("Can't find specified TabItem!")); break; } } catch (Exception e) { exception = e; } if (exception == null) { OnError(null); } else { OnError(exception); } }
public static string ExportToXaml(OutlinerDocument Document, MainWindow wnd) { FlowDocument wholeDocument = new FlowDocument(); wholeDocument.FontFamily = UVOutliner.Settings.DefaultFontFamily; wholeDocument.FontSize = UVOutliner.Settings.DefaultFontSize; List <OutlinerNote> linearList = new List <OutlinerNote>(); DocumentHelpers.GetLinearNotesList(Document.RootNode, linearList, false); double totalWidth = 0; for (int i = 0; i < Document.ColumnDefinitions.Count; i++) { totalWidth += Document.ColumnDefinitions[i].Width; } // just random if (totalWidth == 0) { totalWidth = 300; } Table table = new Table(); table.LineHeight = 1; table.Margin = new Thickness(0); table.Padding = new Thickness(0); wholeDocument.Blocks.Add(table); for (int i = 0; i < wnd.OutlinerTreeColumns.Count; i++) { int columnId = wnd.GetColumnIdByView(i); TableColumn column = new TableColumn(); column.Width = new GridLength(Document.ColumnDefinitions[columnId].Width / totalWidth, GridUnitType.Star); table.Columns.Add(column); } // add column headers if (Document.ColumnDefinitions.Count > 1) { TableRowGroup rowGroup = new TableRowGroup(); table.RowGroups.Add(rowGroup); TableRow row = new TableRow(); rowGroup.Rows.Add(row); for (int i = 0; i < wnd.OutlinerTreeColumns.Count; i++) { int columnId = wnd.GetColumnIdByView(i); row.Cells.Add(new TableCell(new Paragraph(new Run(Document.ColumnDefinitions[columnId].ColumnName)))); } } TableRowGroup mainRowGroup = new TableRowGroup(); table.RowGroups.Add(mainRowGroup); // add all other columns for (int i = 0; i < linearList.Count; i++) { TableRow tableRow = new TableRow(); OutlinerNote note = linearList[i]; if (note.IsEmpty) { tableRow.Cells.Add(new TableCell(new Paragraph())); mainRowGroup.Rows.Add(tableRow); continue; } for (int c = 0; c < wnd.OutlinerTreeColumns.Count; c++) { int columnId = wnd.GetColumnIdByView(c); FlowDocument flowDocument = linearList[i].Columns[columnId].ColumnData as FlowDocument; if (flowDocument == null) { tableRow.Cells.Add(new TableCell()); continue; } double indent = note.Level * 20; TableCell cell = new TableCell(); tableRow.Cells.Add(cell); Section section = XamlReader.Load(TransformFlowDocumentToSection(flowDocument)) as Section; if (section == null) { continue; } if (columnId != 0) { cell.Blocks.Add(section); } else { Table tbl = new Table(); tbl.LineHeight = 1; tbl.Margin = new Thickness(0); tbl.Padding = new Thickness(0); TableColumn c1 = new TableColumn(); c1.Width = new GridLength(indent + 20 + (Document.CheckboxesVisble ? 20 : 0), GridUnitType.Pixel); TableColumn c2 = new TableColumn(); c2.Width = new GridLength(1, GridUnitType.Auto); tbl.Columns.Add(c1); tbl.Columns.Add(c2); var tmpRowGroup = new TableRowGroup(); var tmpRow = new TableRow(); tmpRowGroup.Rows.Add(tmpRow); tbl.RowGroups.Add(tmpRowGroup); Paragraph para = new Paragraph(); para.Margin = new Thickness(indent, 0, 0, 0); AddImages(Document, note, para); tmpRow.Cells.Add(new TableCell(para)); tmpRow.Cells.Add(new TableCell(section)); cell.Blocks.Add(tbl); } } mainRowGroup.Rows.Add(tableRow); if (note.HasInlineNote) { AddInlineNote(mainRowGroup.Rows, note); } } MemoryStream outStream = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; XmlWriter writer = XmlWriter.Create(outStream, settings); XamlDesignerSerializationManager manager = new XamlDesignerSerializationManager(writer); XamlWriter.Save(wholeDocument, manager); outStream.Seek(0, SeekOrigin.Begin); StreamReader reader = new StreamReader(outStream); return(reader.ReadToEnd()); }
public string ExportReportToHTMLString() { try { FlowDocument new_fd = this.CloneCurrentReportDocument(true); string htmlRep = Helpers.FlowDocToHTMLConverter.ConvertXamlToHtml(XamlWriter.Save(new_fd)); return(htmlRep); } catch (Exception ex) { SiliconStudio.DebugManagers.DebugReporter.Report( SiliconStudio.DebugManagers.MessageType.Error, "EjpControls - Report Editor", "Failed to export Report to HTML" + "\nParent Study ID: " + this.ParentStudyId.ToString() + "\nReport ID: " + this._reportObject.Id.ToString() + "\nError: " + ex.Message); MessageBox.Show("レポートをHTML化した際に失敗しました。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error); return(""); } }
public static void CreateWindowsAccentStyle(bool changeImmediately = false) { var resourceDictionary = new ResourceDictionary(); var color = SystemParameters.WindowGlassColor; resourceDictionary.Add("HighlightColor", color); resourceDictionary.Add("AccentColor", Color.FromArgb(204, color.R, color.G, color.B)); resourceDictionary.Add("AccentColor2", Color.FromArgb(153, color.R, color.G, color.B)); resourceDictionary.Add("AccentColor3", Color.FromArgb(102, color.R, color.G, color.B)); resourceDictionary.Add("AccentColor4", Color.FromArgb(51, color.R, color.G, color.B)); resourceDictionary.Add("HighlightBrush", new SolidColorBrush((Color)resourceDictionary["HighlightColor"])); resourceDictionary.Add("AccentColorBrush", new SolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("AccentColorBrush2", new SolidColorBrush((Color)resourceDictionary["AccentColor2"])); resourceDictionary.Add("AccentColorBrush3", new SolidColorBrush((Color)resourceDictionary["AccentColor3"])); resourceDictionary.Add("AccentColorBrush4", new SolidColorBrush((Color)resourceDictionary["AccentColor4"])); resourceDictionary.Add("WindowTitleColorBrush", new SolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("ProgressBrush", new LinearGradientBrush(new GradientStopCollection(new[] { new GradientStop((Color)resourceDictionary["HighlightColor"], 0), new GradientStop((Color)resourceDictionary["AccentColor3"], 1) }), new Point(0.001, 0.5), new Point(1.002, 0.5))); resourceDictionary.Add("CheckmarkFill", new SolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("RightArrowFill", new SolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("IdealForegroundColor", Colors.White); resourceDictionary.Add("IdealForegroundColorBrush", new SolidColorBrush((Color)resourceDictionary["IdealForegroundColor"])); resourceDictionary.Add("AccentSelectedColorBrush", new SolidColorBrush((Color)resourceDictionary["IdealForegroundColor"])); resourceDictionary.Add("MetroDataGrid.HighlightBrush", new SolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("MetroDataGrid.HighlightTextBrush", new SolidColorBrush((Color)resourceDictionary["IdealForegroundColor"])); resourceDictionary.Add("MetroDataGrid.MouseOverHighlightBrush", new SolidColorBrush((Color)resourceDictionary["AccentColor3"])); resourceDictionary.Add("MetroDataGrid.FocusBorderBrush", new SolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("MetroDataGrid.InactiveSelectionHighlightBrush", new SolidColorBrush((Color)resourceDictionary["AccentColor2"])); resourceDictionary.Add("MetroDataGrid.InactiveSelectionHighlightTextBrush", new SolidColorBrush((Color)resourceDictionary["IdealForegroundColor"])); var fileName = Path.Combine(Config.Instance.ConfigDir, "WindowsAccent.xaml"); try { using (var stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (var writer = XmlWriter.Create(stream, new XmlWriterSettings { Indent = true })) XamlWriter.Save(resourceDictionary, writer); } catch (Exception e) { Log.Error("Error creating WindowsAccent: " + e); return; } resourceDictionary = new ResourceDictionary { Source = new Uri(Path.GetFullPath(fileName), UriKind.Absolute) }; ThemeManager.AddAccent(WindowAccentName, resourceDictionary.Source); var oldWindowsAccent = ThemeManager.GetAccent(WindowAccentName); oldWindowsAccent.Resources.Source = resourceDictionary.Source; if (changeImmediately) { ThemeManager.ChangeAppStyle(Application.Current, CurrentAccent, CurrentTheme); } }
/// <summary> /// Save the column layout of lvResults to the application settings. /// </summary> public void PersistColumns() { Properties.Settings.Default.SearchColumns = XamlWriter.Save(((GridView)listView1.View).Columns); }
public CitiesSelection(Country country) { InitializeComponent(); Country = country; for (int i = 0; i < Country.CitiesCount; i++) { var SP = new StackPanel { Name = "City" + i.ToString(), Orientation = Orientation.Horizontal, Height = 70 }; var CityName = new Label { Name = "City" + i.ToString() + "Name", Width = 300, VerticalAlignment = VerticalAlignment.Center }; if (Country.Cities[i].Name == "") { CityName.Content = "Название города " + (i + 1).ToString(); } else if (Country.Cities[i].Name.Length > 17) { CityName.Content = Country.Cities[i].Name.Substring(0, 17) + "..."; } else { CityName.Content = Country.Cities[i].Name; } CityName.Style = this.Resources["LabelStyle"] as Style; SP.Children.Add(CityName); var EmptySpace = new Label { Width = 100 }; SP.Children.Add(EmptySpace); string template = XamlWriter.Save(EditButtonTemplate.Template); StringReader stringReader = new StringReader(template); XmlReader xmlReader = XmlReader.Create(stringReader); var EditButton = new Button { Name = "City" + i.ToString() + "Edit", Width = 60, Height = 60, Template = (ControlTemplate)XamlReader.Load(xmlReader) }; EditButton.Click += CityEdit_Click; SP.Children.Add(EditButton); Cities.Children.Add(SP); if (i != Country.CitiesCount - 1) { var BlackSpace = new Label { Style = this.Resources["Label2Style"] as Style }; Cities.Children.Add(BlackSpace); } } }
public Task <bool> LoadDocumentAsync(string svgFilePath) { if (_isLoadingDrawing || string.IsNullOrWhiteSpace(svgFilePath) || !File.Exists(svgFilePath)) { #if DOTNET40 return(TaskEx.FromResult <bool>(false)); #else return(Task.FromResult <bool>(false)); #endif } string fileExt = Path.GetExtension(svgFilePath); if (!(string.Equals(fileExt, SvgConverter.SvgExt, StringComparison.OrdinalIgnoreCase) || string.Equals(fileExt, SvgConverter.CompressedSvgExt, StringComparison.OrdinalIgnoreCase))) { _svgFilePath = null; #if DOTNET40 return(TaskEx.FromResult <bool>(false)); #else return(Task.FromResult <bool>(false)); #endif } _isLoadingDrawing = true; this.UnloadDocument(true); DirectoryInfo workingDir = _workingDir; if (_directoryInfo != null) { workingDir = _directoryInfo; } _svgFilePath = svgFilePath; _saveXaml = _optionSettings.ShowOutputFile; _embeddedImageVisitor.SaveImages = !_wpfSettings.IncludeRuntime; _embeddedImageVisitor.SaveDirectory = _drawingDir; _wpfSettings.Visitors.ImageVisitor = _embeddedImageVisitor; if (_fileReader == null) { _fileReader = new FileSvgReader(_wpfSettings); _fileReader.SaveXaml = _saveXaml; _fileReader.SaveZaml = false; } var drawingStream = new MemoryStream(); // Get the UI thread's context var context = TaskScheduler.FromCurrentSynchronizationContext(); return(Task <bool> .Factory.StartNew(() => { // var saveXaml = _fileReader.SaveXaml; // _fileReader.SaveXaml = true; // For threaded, we will save to avoid loading issue later... //Stopwatch stopwatch = new Stopwatch(); //stopwatch.Start(); //DrawingGroup drawing = _fileReader.Read(svgFilePath, workingDir); //stopwatch.Stop(); //Trace.WriteLine(string.Format("FileName={0}, Time={1}", // Path.GetFileName(svgFilePath), stopwatch.ElapsedMilliseconds)); DrawingGroup drawing = _fileReader.Read(svgFilePath, workingDir); // _fileReader.SaveXaml = saveXaml; _drawingDocument = _fileReader.DrawingDocument; if (drawing != null) { XamlWriter.Save(drawing, drawingStream); drawingStream.Seek(0, SeekOrigin.Begin); return true; } _svgFilePath = null; return false; }).ContinueWith((t) => { try { if (!t.Result) { _isLoadingDrawing = false; _svgFilePath = null; return false; } if (drawingStream.Length != 0) { DrawingGroup drawing = (DrawingGroup)XamlReader.Load(drawingStream); svgViewer.UnloadDiagrams(); svgViewer.RenderDiagrams(drawing); Rect bounds = svgViewer.Bounds; if (bounds.IsEmpty) { bounds = new Rect(0, 0, svgViewer.ActualWidth, svgViewer.ActualHeight); } zoomPanControl.AnimatedZoomTo(bounds); CommandManager.InvalidateRequerySuggested(); // The drawing changed, update the source... _fileReader.Drawing = drawing; } _isLoadingDrawing = false; return true; } catch { _isLoadingDrawing = false; throw; } }, context)); }
public static string ConvertToXaml(object ui) { return(XamlWriter.Save(ui)); }
public static void SerializeContentTo([NotNull] this ContentControl control, [NotNull] TextWriter writer) => XamlWriter.Save(control.Content, writer);