Search Results

Search found 38 results on 2 pages for 'xamlreader'.

Page 1/2 | 1 2  | Next Page >

  • Silverlight 3 XamlReader Exception not caught

    - by Andrej
    Hi, when I use XamlReader.Load() with an invalid XAML string, the resulting XAMLParseException is not caught although beeing in a try-catch-block: try { UIElement xamlCode = XamlReader.Load(XamlText) as UIElement; } catch (Exception ex) { ErrorText = ex.Message; } The code is called from the Tick-Event of a DispatcherTimer, but also in Events like MouseLeftButtonDown the exception is not caught resulting in a break in the Line where I call .Load(). Does anyone know how to catch this Exception and resume normal programm activity? Thanks, Andrej

    Read the article

  • XAML | When used XamlReader.Parse, not able to refer the items using the LogicalTreeHelper/VisualTre

    - by Roopesh
    Hi, I am setting the dynamic xaml (I am reading the xaml from the DB) for the content of a tab using the below statement. Tab.Content = XamlReader.Parse(xaml, ctx) After setting the content, if I try getting the children using the VisualTreeHelper, but I am not able to get. How ever I dont have this issue when I construct the xaml statically. Here is the code to reading the xaml. Dim XmlDocument = New XmlDataDocument() Dim IID As String = Nothing Dim xaml As String = Nothing Dim Tab As New TabItem Dim TempPanel As XmlNode = Nothing 'Tab.Height = 0 Try XmlDocument.Load(Directory.GetCurrentDirectory & "\Xml\AppFile.xml") pXmlDoc = XmlDocument xaml = XmlDocument.SelectSingleNode("//Grid").OuterXml Dim AsmName As String = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name Dim ctx As ParserContext = New ParserContext() ' New ParserContext() ctx.XamlTypeMapper = New XamlTypeMapper(New String() {AsmName}) ctx.XamlTypeMapper.AddMappingProcessingInstruction("src", "WpfToolkitDataGridTester", AsmName) ctx.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation") ctx.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml") ctx.XmlnsDictionary.Add("src", "clr-namespace:WpfToolkitDataGridTester;assembly=" + AsmName) Tab.Name = "Tab" & Grid1Tab.Items.Count + 1 Tab.Header = "AppFile-1" Tab.BorderThickness = New Thickness(0) Tab.IsSelected = True Tab.Content = XamlReader.Parse(xaml, ctx) Grid1Tab.Items.Add(Tab) Return True Catch ex As Exception Throw End Try Here is the code to access the item after constructing the XAML. For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(myVisual) - 1 Dim childVisual As Visual = CType(VisualTreeHelper.GetChild(myVisual, i), Visual) Select Case childVisual.DependencyObjectType.Name Case "ComboBox" AddHandler CType(childVisual, ComboBox).SelectionChanged, AddressOf ComboBox_SelectChanged Case "CheckBox" AddHandler CType(childVisual, CheckBox).Checked, AddressOf CheckBoxClicked AddHandler CType(childVisual, CheckBox).Unchecked, AddressOf CheckBoxClicked Case "RadioButton" AddHandler CType(childVisual, RadioButton).Checked, AddressOf CheckBoxClicked Case "TabControl" For Each item As System.Windows.Controls.TabItem In CType(childVisual, TabControl).Items EnumVisual(item.Content) Next End Select EnumVisual(childVisual) Next i any help is highly appreciated. Thanks,

    Read the article

  • XamlReader.Parse throws exception on empty String

    - by sub-jp
    In our app, we need to save properties of objects to the same database table regardless of the type of object, in the form of propertyName, propertyValue, propertyType. We decided to use XamlWriter to save all of the given object's properties. We then use XamlReader to load up the XAML that was created, and turn it back into the value for the property. This works fine for the most part, except for empty strings. The XamlWriter will save an empty string as below. <String xmlns="clr-namespace:System;assembly=mscorlib" xml:space="preserve" /> The XamlReader sees this string and tries to create a string, but can't find an empty constructor in the String object to use, so it throws a ParserException. The only workaround that I can think of is to not actually save the property if it is an empty string. Then, as I load up the properties, I can check for which ones did not exist, which means they would have been empty strings. Is there some workaround for this, or is there even a better way of doing this?

    Read the article

  • Serialize WPF component using XamlWriter without default constructor

    - by mizipzor
    Ive found out that you can serialize a wpf component, in my example a FixedDocument, using the XamlWriter and a MemoryStream: FixedDocument doc = GetDocument(); MemoryStream stream = new MemoryStream(); XamlWriter.Save(doc, stream); And then to get it back: stream.Seek(0, SeekOrigin.Begin); FixedDocument result = (FixedDocument)XamlReader.Load(stream); return result; However, now I need to be able to serialize a DocumentPage as well. Which lacks a default constructor which makes the XamlReader.Load call throw an exception. Is there a way to serialize a wpf component without a default constructor?

    Read the article

  • Silverlight 3.0 Custom ListBox DataTemplate has a checkbox, checked event not firing

    - by Bhaskar
    The datatemplate for the ListBox is set dynamically by XamlReader.Load. I am subscribing to Checked event by getting the CheckBox object using VisualTreeHelper.GetChild. This event is not getting fired Code Snippet public void SetListBox() { lstBox.ItemTemplate = XamlReader.Load(@"<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:Name=""DropDownTemplate""><Grid x:Name='RootElement'><CheckBox x:Name='ChkList' Content='{Binding " + TextContent + "}' IsChecked='{Binding " + BindValue + ", Mode=TwoWay}'/></Grid></DataTemplate>") as DataTemplate; CheckBox chkList = (CheckBox)GetChildObject((DependencyObject)_lstBox.ItemTemplate.LoadContent(), "ChkList"); chkList.Checked += delegate { SetSelectedItemText(); }; } public CheckBox GetChildObject(DependencyObject obj, string name) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject c = VisualTreeHelper.GetChild(obj, i); if (c.GetType().Equals(typeof(CheckBox)) && (String.IsNullOrEmpty(name) || ((FrameworkElement)c).Name == name)) { return (CheckBox)c; } DependencyObject gc = GetChildObject(c, name); if (gc != null) return (CheckBox)gc; } return null; } How to handle the checked event? Please help

    Read the article

  • C# Attribute XmlIgnore and XamlWriter class - XmlIgnore not working

    - by Horst Walter
    I have a class, containing a property Brush MyBrush marked as [XmlIgnore]. Nevertheless it is serialized in the stream causing trouble when trying to read via XamlReader. I did some tests, e.g. when changing the visibility (to internal) of the Property it is gone in the stream. Unfortunately I cannot do this in my particular scenario. Did anybody have the same issue and? Do you see any way to work around this? Remark: C# 4.0 as far I can tell This is a method from my Unit Test where I do test the XamlSerialization: // buffer to a StringBuilder StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb, settings); XamlDesignerSerializationManager manager = new XamlDesignerSerializationManager(writer) {XamlWriterMode = XamlWriterMode.Expression}; XamlWriter.Save(testObject, manager); xml = sb.ToString(); Assert.IsTrue(!String.IsNullOrEmpty(xml) && !String.IsNullOrEmpty(xml), "Xaml Serialization failed for " + testObject.GetType() + " no xml string available"); xml = sb.ToString(); MemoryStream ms = xml.StringToStream(); object root = XamlReader.Load(ms); Assert.IsTrue(root != null, "After reading from MemoryStream no result for Xaml Serialization"); In one of my classes I use the Property Brush. In the above code this Unit Tests fails because of a Brush object not serializable is the value. When I remove the Setter (as below, the Unit Test passes. Using the XmlWriter (basically same test as above) it works. In the StringBuffer sb I can see that Property Brush is serialized when the Setter is there and not when removed (most likely another check ignoring the Property because of no setter). Other Properties with [XmlIgnore] are ignored as intended. [XmlIgnore] public Brush MyBrush { get { ..... } // removed because of problem with Serialization // set { ... } }

    Read the article

  • C# WPF XAML Loading

    - by user3713589
    Hi I'd like to inquire on how i can load a WPF Xaml into code so that I can change the values of the attributes of some XAML elements and output it by creating another XAML files. This is so that I can output the same file with values dynamically input by the user. the XamlReader.Load() method cannot be used; it will throw an exception (because they are unable to recognise Window as the root element). I'm using VS2013 and C#.

    Read the article

  • WPF Richtextbox XamlWriter behaviour

    - by Krishna
    I am trying to save some c# source code into the database. Basically I have a RichTextBox that users can type their code and save that to the database. When I copy and paste from the visual studio environment, I would like to preserve the formating etc. So I have chosen to save the FlowDocuments Xaml to the database and set this back to the RichTextBox.Document. My below two function serialise and deserialise the RTB's contents. private string GetXaml(FlowDocument document) { if (document == null) return String.Empty; else{ StringBuilder sb = new StringBuilder(); XmlWriter xw = XmlWriter.Create(sb); XamlDesignerSerializationManager sm = new XamlDesignerSerializationManager(xw); sm.XamlWriterMode = XamlWriterMode.Expression; XamlWriter.Save(document, sm ); return sb.ToString(); } } private FlowDocument GetFlowDocument(string xamlText) { var flowDocument = new FlowDocument(); if (xamlText != null) flowDocument = (FlowDocument)XamlReader.Parse(xamlText); // Set return value return flowDocument; } However when I try to serialise and deserialise the following code, I am noticing this incorrect(?) behaviour using System; public class TestCSScript : MarshalByRefObject { } Serialised XAML is using System; public class TestCSScript : MarshalByRefObject {}{ } Notice the the new set of "{}" What am I doing wrong here... Thanks in advance for the help!

    Read the article

  • Getting Error whileInitializing entities [closed]

    - by R76
    I am new'b as WPF Dev. I am developing Window application in WPF using mvvmlight framework. I have created database in Sqlserver compact 4.0. I have made a Ado.net Entity Data Model. When I trying to initialize the Entity object in service it throws the error like: Error 'The invocation of the constructor on type 'PointOfSale.ViewModels.ProductsViewModel' that matches the specified binding constraints threw an exception.' Line number '7' and line position '10'. stack Trace at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri) at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri) at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri) at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream) at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator) at PointOfSale.MainWindow.InitializeComponent() in e:\VarniApplication\PointOfSale\PointOfSale\MainWindow.xaml:line 1 at PointOfSale.MainWindow..ctor() in E:\VarniApplication\PointOfSale\PointOfSale\MainWindow.xaml.cs:line 27 Inner Exception {"Unable to load the specified metadata resource."} My code: xyzEntities entites; public ctor() { entites = new xyzEntities(); //This line throws an error } I have installed sql server compact 4.0 from web installer 3.0. and added the sql server compact toolbox from the extension manager. Tell me if I am missing something to install or missing something to write code.

    Read the article

  • Unable to find static resource in runtime even while designer can see it

    - by xumix
    So i have this markup: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Werp.MigrationHelper"> <Style TargetType="{x:Type UserControl}" x:Key="WizardPageControl" x:Name="WizardPageControl"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type UserControl}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="10" /> <ColumnDefinition Width="475" /> <ColumnDefinition Width="10" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="10" /> <RowDefinition Height="410"/> <RowDefinition Height="50" /> <RowDefinition Height="10" /> </Grid.RowDefinitions> <StackPanel Orientation="Vertical" Name="MainContent" Grid.Row="1" Grid.Column="1"> <ContentPresenter Content="{TemplateBinding Content}"/> </StackPanel> <StackPanel Grid.Column="1" Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,0,0,10" Height="30"> <Button Name="BackButton" Width="50" xml:space="preserve">&lt; _Back</Button> <Button Name="NextButton" Width="50" Margin="10,0,0,0" xml:space="preserve" IsDefault="True">_Next &gt;</Button> <Button Name="CancelButton" Width="50" Margin="10,0,0,0" IsCancel="True">_Cancel</Button> <Button Name="FinishButton" IsEnabled="True" Width="50" Margin="10,0,0,0">_Finish</Button> </StackPanel> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> <Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Resources\WizardPageControl.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> <UserControl x:Class="Werp.MigrationHelper.WizardPageControl" 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:local="clr-namespace:Werp.MigrationHelper" mc:Ignorable="d"> </UserControl> Then I try to use it: <PageFunction xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Werp.MigrationHelper" x:Class="Werp.MigrationHelper.WizardPage1" x:TypeArguments="local:WizardResult" KeepAlive="True" WindowTitle="Wizard Page 1" > <local:WizardPageControl Style="{StaticResource ResourceKey=WizardPageControl}"> <local:WizardPageControl.Content> qweqweqweqweq </local:WizardPageControl.Content> </local:WizardPageControl> </PageFunction> The VS designer show everything Ok, but in runtime i get System.Windows.Markup.XamlParseException occurred Message='Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '4' and line position '5'. Source=PresentationFramework LineNumber=4 LinePosition=5 StackTrace: at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri) at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri) at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream) at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator) at Werp.MigrationHelper.WizardPage1.InitializeComponent() in d:\Home\Docs\Visual Studio 2008\Projects\csharp\wizardpage1.xaml:line 1 at Werp.MigrationHelper.WizardPage1..ctor(WizardData wizardData) in D:\home\Docs\Visual Studio 2008\Projects\csharp\WizardPage1.xaml.cs:line 12 InnerException: Message=Cannot find resource named 'WizardPageControl'. Resource names are case sensitive. Source=PresentationFramework StackTrace: at System.Windows.StaticResourceExtension.ProvideValue(IServiceProvider serviceProvider) at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProvideValue(MarkupExtension me, IServiceProvider serviceProvider) InnerException: Whats the prolem??

    Read the article

  • HTML to XAML Conversion, Display HTML in RichTextBox

    - by Erika
    Hi, unfortunately im REALLY stuck on this and was wondering in anyone knows how to work around this. I have some html text which i want displayed in a WPF RichTextBox. At the moment, i'm using some helper APIs found http://blogs.msdn.com/wpfsdk/archive/2006/05/25/606317.aspx to convert HTML to XAML. So at the moment i have a xaml data string, but i cant see to find a way to display this correctly within the richtextbox :s i have been trying the following: string xamlData = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(sBody,true); FlowDocument result = XamlReader.Load(new System.Xml.XmlTextReader(new StringReader(xamlData))) as FlowDocument; but this is crashing on the XamlReader.. Any other way will do, i just need to display an HTML string in this RichTextBox or something else! Please Help!

    Read the article

  • Silverlight 4.0: DataTemplate Error

    - by xscape
    Im trying to get the specific template in my resource dictionary. This is my resource dictionary <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:view="clr-namespace:Test.Layout.View" xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><DataTemplate x:Key="LeftRightLayout"> <toolkit:DockPanel> <view:SharedContainerView toolkit:DockPanel.Dock="Left"/> <view:SingleContainerView toolkit:DockPanel.Dock="Right"/> </toolkit:DockPanel> </DataTemplate> However when it gets to XamlReader.Load private static ResourceDictionary GetResource(string resourceName) { ResourceDictionary resource = null; XDocument xDoc = XDocument.Load(resourceName); resource = (ResourceDictionary)XamlReader.Load(xDoc.ToString(SaveOptions.None)); return resource; } The type 'SharedContainerView' was not found because 'clr-namespace:Test.Layout.View' is an unknown namespace. [Line: 4 Position: 56]

    Read the article

  • Linking IronPython to WPF

    - by DonnyD
    I just installed VS2010 and the great new IronPython Tools extension. Currently this extension doesn't yet generate event handlers in code upon double-clicking wpf visual controls. Is there anyone that can provide or point me to an example as to how to code wpf event handlers manually in python. I've had no luck finding any and I am new to visual studio. Upon generating a new ipython wpf project the auto-generated code is: import clr clr.AddReference('PresentationFramework') from System.Windows.Markup import XamlReader from System.Windows import Application from System.IO import FileStream, FileMode app = Application() app.Run(XamlReader.Load(FileStream('WpfApplication7.xaml', FileMode.Open))) and the XAML is: <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WpfApplication7" Height="300" Width="300"> <Button>Click Me</Button> </Window> Any help would be appreciated.

    Read the article

  • Moving to .net 4 results in System.Transactions Critical: 0

    - by john
    Hi I have fully working project in .net 3.5SP1, with EF 1 ORM. I tried to upgrade to .net 4. No issue while upgrading... Then i ran the project and got a NullExecptionError, with no stack trace... and no way to debug. Looking at the output windows i can read this: System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Unhandled exception</Description><AppDomain>OTCSouscriptions.vshost.exe</AppDomain><Exception><ExceptionType>System.NullReferenceException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Object reference not set to an instance of an object.</Message><StackTrace> at System.Windows.StyleHelper.GetInstanceValue(UncommonField`1 dataField, DependencyObject container, FrameworkElement feChild, FrameworkContentElement fceChild, Int32 childIndex, DependencyProperty dp, Int32 i, EffectiveValueEntry&amp;amp; entry) at System.Windows.FrameworkTemplate.ReceivePropertySet(Object targetObject, XamlMember member, Object value, DependencyObject templatedParent) at System.Windows.FrameworkTemplate.&amp;lt;&amp;gt;c__DisplayClass6.&amp;lt;LoadOptimizedTemplateContent&amp;gt;b__4(Object sender, XamlSetValueEventArgs setArgs) at System.Xaml.XamlObjectWriter.OnSetValue(Object eventSender, XamlMember member, Object value) at System.Xaml.XamlObjectWriter.Logic_ApplyPropertyValue(ObjectWriterContext ctx, XamlMember prop, Object value, Boolean onParent) at System.Xaml.XamlObjectWriter.Logic_DoAssignmentToParentProperty(ObjectWriterContext ctx) at System.Xaml.XamlObjectWriter.Logic_AssignProvidedValue(ObjectWriterContext ctx) at System.Xaml.XamlObjectWriter.WriteEndObject() at System.Xaml.XamlWriter.WriteNode(XamlReader reader) at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter) Any help appreciated... Thanks John

    Read the article

  • New TabItem Content ActualHeight crashes Xaml Window

    - by Jack Navarro
    I am able to create new TabItems with Content dynamically to a new window by streaming the Xaml with XamlReader: NewWindow newWindow = new NewWindow(); newWindow.Show(); TabControl myTabCntrol = newWindow.FindName("GBtabControl") as TabControl; StringReader stringReader = new StringReader(XamlGrid); XmlReader xmlReader = XmlReader.Create(stringReader); TabItem myTabItem = new TabItem(); myTabItem.Header = qDealName; myTabItem.Content = (UIElement)XamlReader.Load(xmlReader); myTabCntrol.Items.Add(myTabItem); This works fine. It displays a new grid wrapped in a scrollviewer. The problem is access the TabItem content from the newWindow. TabItem ti = GBtabControl.SelectedItem as TabItem; string scrollvwnm = "scrollViewer" + ti.Header.ToString(); MessageBox.Show(ti.ActualHeight.ToString()); // returns 21.5 ScrollViewer scrlvwr = this.FindName(scrollvwnm) as ScrollViewer; MessageBox.Show(scrollvwnm); // Displays name double checked for accuracy MessageBox.Show(scrlvwr.ActualHeight.ToString()); //Crashes ScrollViewer scrlvwr = ti.FindName(scrollvwnm) as ScrollViewer; MessageBox.Show(scrollvwnm); // Displays name double checked for accuracy MessageBox.Show(scrlvwr.ActualHeight.ToString()); //Also Crashes Is there a method to refresh UI in XAML so the new window is able to access the newly loaded tab item content? Thanks

    Read the article

  • How can I load combo box's data when it has been defined in DataTemplate codebehind ?

    - by Naseem
    Hi, In my silverlight application,I need to have dynamic columns in my DataGrid . So I had to create all the columns and their DataTemplate dynamically .When user wants to edit the column , a combo box will be displayed which has different values based on selected column. For creating each column I have wrote : foreach (var itemFilter in ProductFilterCollection) { DataGridTemplateColumn templateColumn = new DataGridTemplateColumn(); templateColumn.Header = itemFilter.Description.ToString(); templateColumn.CellTemplate = CreateCellTemplate(typeof(TextBlock), itemFilter.Description.ToString()); templateColumn.CellEditingTemplate = CreateEditingTemplate(typeof(ComboBox), itemFilter.Description.ToString()); grdTest.Columns.Add(templateColumn); } Here is the code for creating DataTemplate dynamically. public DataTemplate CreateCellTemplate(Type type, string strBinding) { return (DataTemplate)XamlReader.Load(@"<DataTemplate xmlns=""http://schemas.microsoft.com/client/2007""> <" + type.Name + @" Text=""{Binding " + strBinding + @"}""/> </DataTemplate>"); } public DataTemplate CreateEditingTemplate(Type type, string strBinding) { return (DataTemplate)XamlReader.Load(@"<DataTemplate xmlns=""http://schemas.microsoft.com/client/2007""> <" + type.Name + @" Loaded=""ddlTest_Loaded"" Tag=""{Binding " + strBinding + @"}""/> </DataTemplate>"); } I need to use Loaded="ddlTest_Loaded" in CreateEditingTemplate() ,in order to load the combo box . However it causes exception . When I remove Loaded event it's fine however the combo box is empty. How can I load the combo box when I define it in DataTemplate codebehind.

    Read the article

  • Manually parse string as XAML Attribute

    - by bitbonk
    How does the XAML Parser convert the string "Red" in Foreground="Red" to a SolidColorBrush? Allthough I know the Types have System.ComponentModel.TypeConverter defined, I doupt that the WPF XAML parser acutally always uses those to convert the string to the brush. Are there any XAML APIs apart from XamlReader.Load (wich wants a valid xml string) that I could use to parse a single string as if it where an attibute for a certain property?

    Read the article

  • WPF Reusing Xaml Effectively

    - by Steve
    Hi, I've recently been working on a project using WPF to produce a diagram. In this I must show text alongside symbols that illustrate information associated with the text. To draw the symbols I initially used some png images I had produced. Within my diagram these images appeared blurry and only looked worse when zoomed in on. To improve on this I decided I would use a vector rather than a rastor image format. Below is the method I used to get the rastor image from a file path: protected Image GetSymbolImage(string symbolPath, int symbolHeight) { Image symbol = new Image(); symbol.Height = symbolHeight; BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.UriSource = new Uri(symbolPath); bitmapImage.DecodePixelHeight = symbolHeight; bitmapImage.EndInit(); symbol.Source = bitmapImage; return symbol; } Unfortunately this does not recognise vector image formats. So instead I used a method like the following, where "path" is the file path to a vector image of the format .xaml: public static Canvas LoadXamlCanvas(string path) { //if a file exists at the specified path if (File.Exists(path)) { //store the text in the file string text = File.ReadAllText(path); //produce a canvas from the text StringReader stringReader = new StringReader(text); XmlReader xmlReader = XmlReader.Create(stringReader); Canvas c = (Canvas)XamlReader.Load(xmlReader); //return the canvas return c; } return null; } This worked but drastically killed performance when called repeatedly. I found the logic necessary for text to canvas conversion (see above) was the main cause of the performance problem therefore embedding the .xaml images would not alone resolve the performance issue. I tried using this method only on the initial load of my application and storing the resulting canvases in a dictionary that could later be accessed much quicker but I later realised when using the canvases within the dictionary I would have to make copies of them. All the logic I found online associated with making copies used a XamlWriter and XamlReader which would again just introduce a performance problem. The solution I used was to copy the contents of each .xaml image into its own user control and then make use of these user controls where appropriate. This means I now display vector graphics and performance is much better. However this solution to me seems pretty clumsy. I'm new to WPF and wonder if there is some built in way of storing and reusing xaml throughout an application? Apologies for the length of this question. I thought having a record of my attempts might help someone with any similar problem. Thanks.

    Read the article

  • Creating a Silverlight DataTemplate in code

    - by Nick R
    How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight. Edit: Here's the code I'm now using this for, based on the answer from Santiago below. public DataTemplate Create(Type type) { return (DataTemplate)XamlReader.Load( @"<DataTemplate xmlns=""http://schemas.microsoft.com/client/2007""> <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/> </DataTemplate>" ); } This works really nicely and allows me to change the binding on the fly.

    Read the article

  • Convert XAML to FlowDocument to display in RichTextBox in WPF

    - by Erika
    I have some HTML, which i am converting to XAML using the library provided by Microsoft string t = HtmlToXamlConverter.ConvertHtmlToXaml(mail.HtmlDataString,true); now, from http://stackoverflow.com/questions/1449121/how-to-insert-xaml-into-richtextbox i am using the following: private static FlowDocument SetRTF(string xamlString) { StringReader stringReader = new StringReader(xamlString); System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(stringReader); Section sec = XamlReader.Load(xmlReader) as Section; FlowDocument doc = new FlowDocument(); while (sec.Blocks.Count > 0) doc.Blocks.Add(sec.Blocks.FirstBlock); return doc; } This however keeps crashing unfortunately =/ Does anyone have any clue on how to display XAML text in a RichTextBox please?

    Read the article

  • Assign binding path at runtime in WPF DataTemplate

    - by Abiel
    I am writing a WPF program in C# in which I have a ListView for which the columns will be populated at runtime. I would like to use a custom DataTemplate for the GridViewColumn objects in the ListView. In the examples I have seen where the number of columns is fixed in advance, a custom DataTemplate is often created using something like the XAML below. <DataTemplate x:Key="someKey"> <TextBlock Text="{Binding Path=FirstName}" /> </DataTemplate> This DataTemplate could also later be assigned to GridViewColumn.CellTemplate in the code-behind by calling FindResource("someKey"). However, this alone is of no use to me, because in this example the Path element is fixed to FirstName. Really I need something where I can set the Path in code. It is my impression that something along these lines may be possible if XamlReader is used, but I'm not sure how in practice I would do this. Any solutions are greatly appreciated.

    Read the article

  • iterating resourcedictionary xaml file

    - by Sdry
    I am trying to display an amount of colorpicker controls depending on an amount of colors in a xamnl resourcedictionary file. For some reason I can't figure out the right way to do this. When loading it in through a XAMLReader to a ResourcesDictionary Object, I m not sure what is the best way to iterate over it. I had first tried to handle it as xml, using XDocument.Elements() which gave an empty IEnumerable when trying to get al the elements. What is the best way to do this ?

    Read the article

  • How to add handler in dynamic datatemplate

    - by Phillip Ngan
    I am successfully declaring a data template in a code behind as follows: private static DataTemplate CreateTemplate(string sortMemberPath, HorizontalAlignment horzAlignment) { const string xamlFormat = "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" >" + "<StackPanel > " + " <TextBlock Margin=\"2,0\" VerticalAlignment=\"Center\" HorizontalAlignment=\"_HALIGNMENT_\" " + " Text=\"hello there\"> " + " </TextBlock> " + "</StackPanel>" + "</DataTemplate>"; return (DataTemplate) XamlReader.Load(xamlReturned); } But now I want to add a size changed handler by changing the line: + "<StackPanel > " to + "<StackPanel SizeChanged="SizeChangedHandler" > " I have the method "SizeChangedHandler" declared in the code behind. This results in a xaml parse error when the control attempts to load at runtime. I suspect that it can't find the handler "SizeChangedHandler". How can I specify this handler so that the xaml parser is happy.

    Read the article

  • how to dynamically add button to SilverLight datagrid

    - by Grayson Mitchell
    I have a datagrid that I want to add a button/s to at runtime. I have managed to do this with the below code: DataGridTemplateColumn templateCol = new DataGridTemplateColumn(); templateCol.CellTemplate = (System.Windows.DataTemplate)XamlReader.Load( @"<DataTemplate xmlns='http://schemas.microsoft.com/client/2007' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'> <Button Content='" + item.Value.Label + @"'/> </DataTemplate>"); _dataGrid.Columns.Add(templateCol); The problem is that I can't work out how to add a click event. I want to add a click event with a parameter corresponding to the row id...

    Read the article

1 2  | Next Page >