locked
Create custom property on xaml element with change notifications

    Question

  • Hi,

    I want to create a custom property on TextBlocks throughout my app which I can then use to set the font weight.

    I need to support change notifications for the property so I can change the resource in a settings page and then immediately see all TextBlocks with the property affected throughout the app.

    I'm planning on simply changing the resource in a SettingsPage as so -

    Application.Current.Resources["FontWeight"] = FontWeights.SemiLight

    And expect the textblocks to all update their FontWeights

    Thanks


    Saturday, November 15, 2014 3:41 PM

Answers

All replies

  • You can do this with an Attached Property. Search on that term and you should find docs and examples.

    VS has a "propa" snippet that can help.

    Saturday, November 15, 2014 6:25 PM
    Owner
  • So far I have come up with the following property, the only part I cannot get to work is how to make the notification trigger when Application.Current.Resources["CustomFontWeight"] is changed

    public static readonly DependencyProperty FontWeightProperty = DependencyProperty.RegisterAttached("FontWeight", typeof(string), typeof(MyExtensions), new PropertyMetadata(0, OnFontWeightChanged)); public static string GetFontWeight(DependencyObject obj) { return (string)obj.GetValue(TextProperty); } public static void SetFontWeight(DependencyObject obj, string value) { var textblock = obj as TextBlock; if (textblock == null) { return; } textblock .FontWeight = (FontWeight)Application.Current.Resources["CustomFontWeight"]; } private static void OnFontWeightChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var textblock = d as RichTextBlock; if (textblock == null) { return; } textblock .FontWeight = (FontWeight)Application.Current.Resources["CustomFontWeight"]; }

    Saturday, November 15, 2014 6:48 PM
  • Hi Brad,

    You can't detect the resource change directly. Instead create a property that you can bind to and change the resource only in that property.

    --Rob

    Friday, November 21, 2014 1:17 AM
    Owner