Silverlight UserControl Custom Property Binding

前端 未结 3 1424
生来不讨喜
生来不讨喜 2021-02-07 08:36

What is the proper way to implement Custom Properties in Silverlight UserControls?

Every \"Page\" in Silverlight is technically a UserControl (they are derived from the

3条回答
  •  生来不讨喜
    2021-02-07 09:28

    The Issue was the UserControl was throwing a DataBinding error (visible in the Output window while debugging)

    Because The UserControl's DataContext was set to "Self" in its own xaml, it was looking for the MainPageSelectedText within its own context (it was not looking for the MainPageSelectedText within the "MainPage" which is where you might think it would look, because when you are physically writing/looking at the code that is what is in "context")

    I was able to get this "working" by setting the Binding in the code behind. Setting the binding in the code behind is the only way to set the UserControl itself as the "Source" of the binding. But this only works if the Binding is TwoWay. OneWay binding will break this code. A better solution altogether would be to create a Silverlight Control, not a UserControl.

    See Also:

    http://social.msdn.microsoft.com/Forums/en-US/silverlightcontrols/thread/052a2b67-20fc-4f6a-84db-07c85ceb3303

    http://msdn.microsoft.com/en-us/library/cc278064%28VS.95%29.aspx

    MyCustomUserControl.xaml

    
     
      
       
       
        
       
      
     
    
    

    MyCustomUserControl.xaml.cs

    namespace SilverlightCustomUserControl
    {
     public partial class MyCustomUserControl : UserControl
     {
    
      public string SelectedText
      {
       get { return (string)GetValue(SelectedTextProperty); }
       set { SetValue(SelectedTextProperty, value); }
      }
    
      public static readonly DependencyProperty SelectedTextProperty =
        DependencyProperty.Register("SelectedText", typeof(string), typeof(MyCustomUserControl), new PropertyMetadata("", SelectedText_PropertyChangedCallback));
    
    
      public MyCustomUserControl()
      {
       InitializeComponent();
    
                   //SEE HERE
       UserControlTextBox.SetBinding(TextBox.TextProperty, new Binding() { Source = this, Path = new PropertyPath("SelectedText"), Mode = BindingMode.TwoWay });
       UserControlTextBlock.SetBinding(TextBlock.TextProperty, new Binding() { Source = this, Path = new PropertyPath("SelectedText") });
                   //SEE HERE
      }
    
      private static void SelectedText_PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
      {
       //empty
      }
    
     }
    }
    

提交回复
热议问题