Niya
Niya

Reputation: 253

How does the Visual Studio Intellisense know how to list predefined brushes for Brush type properties in WPF XAML?

WPF XAML Intellisense

Whenever referring to a property of type Brush in a WPF project through XAML, the intellisense shows a list of possible choices from among a predefined set of Brush objects. The interesting thing is that this list comes from a completely different class. This list of predefined Brush objects actually comes from a class called Brushes. Each predefined Brush is a static readonly property of the Brushes type. How is the Brushes class that contains the predefined Brush objects associated with the Brush type itself? And how can I replicate this behavior for my own custom types?

I'd like to be able to define my own types with predefined choices while having the intellisense offer the choices as it does with the Brush type.

To clarify, I want to know how to replicate the intellisense behavior for any custom type I might create. When you attempt to assign a value to the Background property of UIElement in WPF, the intellisense gives you a choice of pre-defined Brush objects because the data type of the Background property is of type Brush.

If I decided to create a property of a custom type. Lets say the property name is Location and it's of type Country. I have another static class called Countries and in the Countries class, there are static readonly properties to represent different countries. Each of these static properties returns a Country object. I want when I attempt to assign a value to the Location property of my custom object in XAML, it lists the members of the Countries class the same way it would do with the Brushes class. I want to know how to get this intellisense behavior for my custom Country type.

Upvotes: 1

Views: 184

Answers (1)

DasiyTian_1203
DasiyTian_1203

Reputation: 1086

You can implement it by creating an attached DependencyProperty which type is your custome enum type, here is my demo code for you:

class CountryManager : DependencyObject
{
    public static CountryEnum GetCountry(DependencyObject obj)
    {
        return (CountryEnum)obj.GetValue(CountryProperty);
    }

    public static void SetCountry(DependencyObject obj, CountryEnum value)
    {
        obj.SetValue(CountryProperty, value);
    }

    public static readonly DependencyProperty CountryProperty =
        DependencyProperty.RegisterAttached("Country", typeof(CountryEnum), typeof(CountryManager), new PropertyMetadata(CountryEnum.Country1));
}

public enum CountryEnum
{
    Country1,
    Country2,
    Country3,
    Country4,
    Country5,
    Country6,
    Country7,
    Country8,
    Country9
};

To use it like below picture shown: enter image description here

Upvotes: 1

Related Questions