How to set up a WPF data table in tree code?

struct Drink { public string Name { get; private set; } public int Popularity { get; private set; } public Drink ( string name, int popularity ) : this ( ) { this.Name = name; this.Popularity = popularity; } } List<Drink> coldDrinks = new List<Drink> ( ){ new Drink ( "Water", 1 ), new Drink ( "Fanta", 2 ), new Drink ( "Sprite", 3 ), new Drink ( "Coke", 4 ), new Drink ( "Milk", 5 ) }; } } 

So that I can see the Name property for treeview element names.

+2
source share
3 answers

Reid had already considered the Build Your Own XAML approach, but just to give an illustration of the FrameworkElementFactory approach, it would look something like this.

First create an FEF:

 var fef = new FrameworkElementFactory(typeof(TextBlock)); fef.SetBinding(TextBlock.TextProperty, new Binding("Name")); 

Then create a DataTemplate with its VisualTree set to factory:

 DataTemplate dt = new DataTemplate { VisualTree = fef }; 

Although, as Reid notes, the FrameworkElementFactory approach is officially deprecated, it is still widely used, I think because the structure of the XAML lines seems so ragged. (Although the FEF approach quickly becomes insanely complex if you have a non-trivial template ...!)

+2
source

There are two approaches. The easiest way is to simply generate xaml and parse it at runtime:

 string xaml = "<DataTemplate><TextBlock Text=\"{Binding Name}\"/></DataTemplate>"; MemoryStream sr = new MemoryStream(Encoding.ASCII.GetBytes(xaml)); ParserContext pc = new ParserContext(); pc.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); pc.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); DataTemplate datatemplate = (DataTemplate)XamlReader.Load(sr, pc); treeView1.Resources.Add("dt", datatemplate); 

The second option is to use the FrameworkElementFactory class. However, it is rather complicated, and difficult "right." Since MSDN now refers to this as deprecated, I will not include code for demonstration ...

+7
source

Instead of creating your own XAML, for example, Reed said that you can get a XAML control using

 String myXAML = System.Windows.Markup.XamlWriter.Save(yourControl.Template) 

Then you can edit the XAML and create your controltemplate / datatemplate file back

 var xamlStream = new MemoryStream(System.Text.Encoding.Default.GetBytes(myXAML)); _buttonControlTemplate = (ControlTemplate)System.Windows.Markup.XamlReader.Load(xamlStream); 
+4
source

Source: https://habr.com/ru/post/1305364/