#1,142 – Setting Attached Property Value from Code

You can change the value of an attached property for a given control from code by using the SetValue or SetCurrentValue methods.  You call these methods on the control that the property is attached to, passing in a reference to the property and the new value.  (SetCurrentValue is preferred, to avoid overwriting a local value).

Below, we set a value for MyAttProps.Important in XAML, but also wire up a Click event to allow changing the value from code.

        <Label x:Name="lblHi" Content="Hi there"
               loc:MyAttProps.Important="True"
               Background="AliceBlue"/>
        <Button Content="Change Content"
                Click="Button_Click"/>

In the code-behind, we use SetCurrentValue to change the value.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            bool impValue = (bool)lblHi.GetValue(MyAttProps.ImportantProperty);

            lblHi.SetCurrentValue(MyAttProps.ImportantProperty, !impValue);
        }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,142 – Setting Attached Property Value from Code

  1. Pingback: Dew Drop – August 22, 2014 (#1840) | Morning Dew

Leave a comment