Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 92749
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T23:14:10+00:00 2026-05-10T23:14:10+00:00

For those who like a good WPF binding challenge: I have a nearly functional

  • 0

For those who like a good WPF binding challenge:

I have a nearly functional example of two-way binding a CheckBox to an individual bit of a flags enumeration (thanks Ian Oakes, original MSDN post). The problem though is that the binding behaves as if it is one way (UI to DataContext, not vice versa). So effectively the CheckBox does not initialize, but if it is toggled the data source is correctly updated. Attached is the class defining some attached dependency properties to enable the bit-based binding. What I’ve noticed is that ValueChanged is never called, even when I force the DataContext to change.

What I’ve tried: Changing the order of property definitions, Using a label and text box to confirm the DataContext is bubbling out updates, Any plausible FrameworkMetadataPropertyOptions (AffectsRender, BindsTwoWayByDefault), Explicitly setting Binding Mode=TwoWay, Beating head on wall, Changing ValueProperty to EnumValueProperty in case of conflict.

Any suggestions or ideas would be extremely appreciated, thanks for anything you can offer!

The enumeration:

[Flags] public enum Department : byte {     None = 0x00,     A = 0x01,     B = 0x02,     C = 0x04,     D = 0x08 } // end enum Department 

The XAML usage:

CheckBox Name='studentIsInDeptACheckBox'          ctrl:CheckBoxFlagsBehaviour.Mask='{x:Static c:Department.A}'          ctrl:CheckBoxFlagsBehaviour.IsChecked='{Binding Path=IsChecked, RelativeSource={RelativeSource Self}}'          ctrl:CheckBoxFlagsBehaviour.Value='{Binding Department}' 

The class:

/// <summary> /// A helper class for providing bit-wise binding. /// </summary> public class CheckBoxFlagsBehaviour {     private static bool isValueChanging;      public static Enum GetMask(DependencyObject obj)     {         return (Enum)obj.GetValue(MaskProperty);     } // end GetMask      public static void SetMask(DependencyObject obj, Enum value)     {         obj.SetValue(MaskProperty, value);     } // end SetMask      public static readonly DependencyProperty MaskProperty =         DependencyProperty.RegisterAttached('Mask', typeof(Enum),         typeof(CheckBoxFlagsBehaviour), new UIPropertyMetadata(null));      public static Enum GetValue(DependencyObject obj)     {         return (Enum)obj.GetValue(ValueProperty);     } // end GetValue      public static void SetValue(DependencyObject obj, Enum value)     {         obj.SetValue(ValueProperty, value);     } // end SetValue      public static readonly DependencyProperty ValueProperty =         DependencyProperty.RegisterAttached('Value', typeof(Enum),         typeof(CheckBoxFlagsBehaviour), new UIPropertyMetadata(null, ValueChanged));      private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)     {         isValueChanging = true;         byte mask = Convert.ToByte(GetMask(d));         byte value = Convert.ToByte(e.NewValue);          BindingExpression exp = BindingOperations.GetBindingExpression(d, IsCheckedProperty);         object dataItem = GetUnderlyingDataItem(exp.DataItem);         PropertyInfo pi = dataItem.GetType().GetProperty(exp.ParentBinding.Path.Path);         pi.SetValue(dataItem, (value & mask) != 0, null);          ((CheckBox)d).IsChecked = (value & mask) != 0;         isValueChanging = false;     } // end ValueChanged      public static bool? GetIsChecked(DependencyObject obj)     {         return (bool?)obj.GetValue(IsCheckedProperty);     } // end GetIsChecked      public static void SetIsChecked(DependencyObject obj, bool? value)     {         obj.SetValue(IsCheckedProperty, value);     } // end SetIsChecked      public static readonly DependencyProperty IsCheckedProperty =         DependencyProperty.RegisterAttached('IsChecked', typeof(bool?),         typeof(CheckBoxFlagsBehaviour), new UIPropertyMetadata(false, IsCheckedChanged));      private static void IsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)     {         if (isValueChanging) return;          bool? isChecked = (bool?)e.NewValue;         if (isChecked != null)         {             BindingExpression exp = BindingOperations.GetBindingExpression(d, ValueProperty);             object dataItem = GetUnderlyingDataItem(exp.DataItem);             PropertyInfo pi = dataItem.GetType().GetProperty(exp.ParentBinding.Path.Path);              byte mask = Convert.ToByte(GetMask(d));             byte value = Convert.ToByte(pi.GetValue(dataItem, null));              if (isChecked.Value)             {                 if ((value & mask) == 0)                 {                     value = (byte)(value + mask);                 }             }             else             {                 if ((value & mask) != 0)                 {                     value = (byte)(value - mask);                 }             }              pi.SetValue(dataItem, value, null);         }     } // end IsCheckedChanged      /// <summary>     /// Gets the underlying data item from an object.     /// </summary>     /// <param name='o'>The object to examine.</param>     /// <returns>The underlying data item if appropriate, or the object passed in.</returns>     private static object GetUnderlyingDataItem(object o)     {         return o is DataRowView ? ((DataRowView)o).Row : o;     } // end GetUnderlyingDataItem } // end class CheckBoxFlagsBehaviour 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T23:14:11+00:00Added an answer on May 10, 2026 at 11:14 pm

    You could use a value converter. Here’s a very specific implementation for the target Enum, but would not be hard to see how to make the converter more generic:

    [Flags] public enum Department {     None = 0,     A = 1,     B = 2,     C = 4,     D = 8 }  public partial class Window1 : Window {     public Window1()     {         InitializeComponent();          this.DepartmentsPanel.DataContext = new DataObject         {             Department = Department.A | Department.C         };     } }  public class DataObject {     public DataObject()     {     }      public Department Department { get; set; } }  public class DepartmentValueConverter : IValueConverter {     private Department target;      public DepartmentValueConverter()     {     }      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)     {         Department mask = (Department)parameter;         this.target = (Department)value;         return ((mask & this.target) != 0);     }      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)     {         this.target ^= (Department)parameter;         return this.target;     } } 

    And then use the converter in the XAML:

    <Window.Resources>     <l:DepartmentValueConverter x:Key='DeptConverter' /> </Window.Resources>   <StackPanel x:Name='DepartmentsPanel'>     <CheckBox Content='A'               IsChecked='{Binding                              Path=Department,                             Converter={StaticResource DeptConverter},                             ConverterParameter={x:Static l:Department.A}}'/>     <!-- more -->  </StackPanel> 

    EDIT: I don’t have enough ‘rep’ (yet!) to comment below so I have to update my own post 🙁

    In the last comment Steve Cadwallader says: ‘but when it comes to two-way binding the ConvertBack falls apart’, well I’ve updated my sample code above to handle the ConvertBack scenario; I’ve also posted a sample working application here (edit: note that the sample code download also includes a generic version of the converter).

    Personally I think this is a lot simpler, I hope this helps.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 52k
  • Answers 52k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • added an answer I think what you're doing is fine. As far as… May 11, 2026 at 6:38 am
  • added an answer It looks like this code isn't the true cause of… May 11, 2026 at 6:38 am
  • added an answer Taken from lytebyte, you've got two options: Shift + F10… May 11, 2026 at 6:38 am

Top Members

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.