1: using System;
2: using System.Collections.Generic;
3: using System.ComponentModel;
4: using System.Windows.Markup;
5: using System.Xaml;
6:
7: namespace ReferenceExample
8: {
9:
10: //when run, this program creates the following output:
11: /*
12: <DatabaseCollection Capacity="4" xmlns="clr-namespace:ReferenceExample;assembly=ReferenceExample">
13: <Table Name="Customer" />
14: <Table Name="Order" />
15: <Relationship Cardinality="OneToMany" From="Customer" To="Order" />
16: <Relationship Cardinality="OneToOne" From="Customer" />
17: </DatabaseCollection>
18: */
19:
20: class Program
21: {
22: static void Main(string[] args)
23: {
24: Table t1 = new Table();
25: t1.Name = "Customer";
26: Table t2 = new Table();
27: t2.Name = "Order";
28: Relationship r1 = new Relationship();
29: r1.From = t1;
30: r1.To = t2;
31: r1.Cardinality = Cardinality.OneToMany;
32: Relationship r2 = new Relationship();
33: r2.From = t1;
34:
35: DatabaseCollection dc = new DatabaseCollection();
36: dc.Add(t1);
37: dc.Add(t2);
38: dc.Add(r1);
39: dc.Add(r2);
40:
41: string xamlString = XamlServices.Save(dc);
42: Console.WriteLine(xamlString);
43:
44: Console.WriteLine("--press any key--");
45: Console.ReadKey();
46: }
47: }
48:
49: public abstract class DatabaseObject {}
50:
51: public class DatabaseCollection : List<DatabaseObject> {}
52:
53: [RuntimeNameProperty("Name")]
54: public class Table : DatabaseObject
55: {
56: public string Name { get; set; }
57: }
58: public class Relationship : DatabaseObject
59: {
60: [TypeConverter(typeof(NameReferenceConverter2))]
61: [DefaultValue(null)]
62: public Table From { get; set; }
63:
64: [TypeConverter(typeof(NameReferenceConverter2))]
65: [DefaultValue(null)]
66: public Table To { get; set; }
67:
68: public Cardinality Cardinality { get; set; }
69: }
70:
71: public enum Cardinality
72: {
73: OneToOne,
74: OneToMany,
75: ManyToMany,
76: }
77:
78: //In .NET 4 Beta1, System.Xaml.NameReferenceConverter doesn't have ConvertTo/CanConvertTo implemented.
79: //Working around with a version hard coded for this scenario...
80: public class NameReferenceConverter2 : NameReferenceConverter
81: {
82: public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
83: {
84: return destinationType == typeof(string);
85: }
86: public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
87: {
88: Table table = value as Table;
89: return table.Name;
90: }
91: }
92:
93: }