Setting a custom property within a WPF/Silverlight page

后端 未结 10 1221
萌比男神i
萌比男神i 2020-12-14 15:10

This sounds like it should be simple. I have a Page declared in XAML in the normal way (i.e. with "Add new item...") and it has a custom property. I\'

10条回答
  •  轮回少年
    2020-12-14 15:33

    You would need to make it an attachable property as Pavel noted, then you can write something like this

    
        
            
        
    
    

    However, with only this code-behind, you will get this error instead:

    The attachable property 'MyProperty' was not found in type 'SkeetPage'.

    The attached property 'SkeetPage.MyProperty' is not defined on 'Page' or one of its base classes.


    Edit

    Unfortunately, you have to use Dependency Properties. Here's a working example

    Page

    
       
        
            
        
    
    

    Code-behind

    using System.Windows;
    using System.Windows.Controls;
    
    namespace JonSkeetTest
    {
        public partial class SkeetPage
        {
            public SkeetPage()
            {
                InitializeComponent();
            }
    
            public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register(
              "MyProperty",
              typeof(string),
              typeof(Page),
              new FrameworkPropertyMetadata(null,
                  FrameworkPropertyMetadataOptions.AffectsRender
              )
            );
    
            public static void SetMyProperty(UIElement element, string value)
            {
                element.SetValue(MyPropertyProperty, value);
            }
            public static string GetMyProperty(UIElement element)
            {
                return element.GetValue(MyPropertyProperty).ToString();
            }
    
            public string MyProperty
            {
                get { return GetValue(MyPropertyProperty).ToString(); }
                set { SetValue(MyPropertyProperty, value); }
            }
    
            private void ButtonTest_Pressed(object sender, RoutedEventArgs e)
            {
                MessageBox.Show(MyProperty);
            }
        }
    }
    

    If you press the button, you will see "Testing..." in a MessageBox.

提交回复
热议问题