简体   繁体   中英

XAML - Comma-Delimited Dependency Property

I have a custom class called AppPreferences. This class has a dependency property called Color. This dependency property represents an enumerated value of the type Colors (which is a custom enumerator). My code for AppPreferences is shown here:

public class AppPreferences
{
  public static readonly DependencyProperty ColorProperty = DependencyProperty.RegisterAttached(
  "Color",
  typeof(MyServiceProxy.Colors),
  typeof(AppPreferences),
  new PropertyMetadata(MyServiceProxy.Colors.DEFAULT, new   PropertyChangedCallback(OnColorChanged))
  );

  private static void OnColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    // Do Stuff
  }
}

As a developer, I add this to my UI elements to help determine the color. For instance, I'll do something like this:

<TextBox custom:AppPreferences.Color="Black" ... />

I now have a need to support fallback colors. In other words, I want to be able to provide a comma-delimited list of Colors values similar to the following:

<TextBox custom:AppPreferences.Color="Black,Blue" ... />

My question is, how do I update my dependency property and OnColorChanged event handler to support multiple values?

Thank you!

The mechanism you're trying to achieve is called "Attached properties".

Read this for info.

Here is a short code excerpt that does it all:

public static readonly DependencyProperty IsBubbleSourceProperty = 
 DependencyProperty.RegisterAttached(
  "IsBubbleSource",
  typeof(Boolean),
  typeof(AquariumObject),
  new FrameworkPropertyMetadata(false, 
    FrameworkPropertyMetadataOptions.AffectsRender)
);
public static void SetIsBubbleSource(UIElement element, Boolean value)
{
  element.SetValue(IsBubbleSourceProperty, value);
}
public static Boolean GetIsBubbleSource(UIElement element)
{
  return (Boolean)element.GetValue(IsBubbleSourceProperty);
}

Read this to get more on comma-separated enumerations in Xaml.

Also you may want checkout this .

You should ensure that you have a flagwise enumeration in order to allow this syntax. This is possible by adding the FlagsAttribute to your enumeration.

[Flags]
enum Colors
{
    Black,
    ...
}

For flagwise enumerations, the behavior is based on the Enum.Parse method. You can specify multiple values for a flagwise enumeration by separating each value with a comma. However, you cannot combine enumeration values that are not flagwise . For instance, you cannot use the comma syntax to attempt to create a Trigger that acts on multiple conditions of a nonflag enumeration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM