示例#1
0
        private static void ProcessField(ClassTemplate source, INamedTypeSymbol classSymbol, INamedTypeSymbol attributeSymbol, IFieldSymbol fieldSymbol)
        {
            var fieldName = fieldSymbol.Name;
            var fieldType = fieldSymbol.Type;

            string propertyName = GenerateName(fieldName);

            var attributeData   = fieldSymbol.GetAttributes().Single(ad => ad.AttributeClass.Equals(attributeSymbol, SymbolEqualityComparer.Default));
            var initialValueOpt = attributeData.NamedArguments.SingleOrDefault(kvp => kvp.Key == "InitialValue").Value;

            var dependencyPropertyValue = initialValueOpt.Value is null ?
                                          @$ "DependencyProperty.Register(" "{propertyName}" ", typeof({fieldType}), typeof({classSymbol.Name}))" :
                                          @$ "DependencyProperty.Register(" "{propertyName}" ", typeof({fieldType}), typeof({classSymbol.Name}), new PropertyMetadata({initialValueOpt.ToCSharpString()}))";

            source
            .WithField(
                new FieldTemplate()
                .WithModifiers(Modifier.Public, Modifier.Static, Modifier.Readonly)
                .WithType("DependencyProperty")
                .WithName(propertyName + DependencyPropertySuffix)
                .WithValue(dependencyPropertyValue))
            .WithProperty(
                new PropertyTemplate()
                .WithType(fieldType.ToString())
                .WithName(propertyName)
                .WithGetter(
                    new GetterTemplate()
                    .WithCode(
                        new CodeBlockTemplate()
                        .WithLine($"this.{fieldName} = ({fieldType})this.GetValue({propertyName + DependencyPropertySuffix});")
                        .WithLine($"return ({fieldType})this.GetValue({propertyName + DependencyPropertySuffix});")))
                .WithSetter(
                    new SetterTemplate()
                    .WithCode(
                        new CodeBlockTemplate()
                        .WithLine($"this.{fieldName} = value;")
                        .WithLine($"this.SetValue({propertyName + DependencyPropertySuffix}, value);"))));
        }