WPF button extension to store data in a new property

I want to extend the WPF button to store some additional data, similar to the current "Tag" property. Attached properties way forward? The data I want to save will be a URL link string, for example, I would like to do something like:

<Button Tag="BBC World News" URLLink="http://www.bbc.co.uk"/>

Can someone help me figure out how to extend the button?

Many thanks

Jay

+3
source share
5 answers

You can use the attached property :

public class ButtonBehavior
{
     public static readonly DependencyProperty UrlLinkProperty =
            DependencyProperty.RegisterAttached("UrlLink",
                                                typeof(ButtonBase),
                                                typeof(ButtonBehavior),
                                                new FrameworkPropertyMetadata(null));

     public static string GetUrlLink(DependencyObject d)
     {
          return (string)d.GetValue(UrlLinkProperty);
     }

     public static void SetUrlLink(DependencyObject d, string value)
     {
          d.SetValue(UrlLinkProperty, value);
     }
}

Then you can declare your button as follows:

<Button Tag="BBC World News" ButtonBehavior.UrlLink="http://www.bbc.co.uk" Click="btnArticleView"/>

And you press the handler, which will look like this:

 protected void btnArticleView(object sender, RoutedEventArgs e)
 {

     Button rb = sender as Button;
     string TheTitle = rb.Tag.ToString();
     string TheURL = ButtonBehavior.GetUrlLink(rb);

     //  Further code here

 }
+5
source

Define an attached property like this

 public static readonly DependencyProperty UrlLinkProperty =
        DependencyProperty.RegisterAttached("UrlLink",
                                            typeof(String),
                                            typeof(ButtonBehavior)
                                            new FrameworkPropertyMetadata(null));
+1

. . Datacontext , . .

0

.

, . . , , "URL-" "URL-". , click Button. :

 protected void btnArticleView(object sender, RoutedEventArgs e)
    {

     Button rb = sender as Button;
     string TheTitle = rb.Tag.ToString();
     string TheURL = rb.URLLink.ToString();

     //  Further code here

}

XAML:

<Button Tag="BBC World News" URLLink="http://www.bbc.co.uk" Click="btnArticleView"/>

0

, , ...

you can always create a custom class "MyURL" with 2 properties "URLText" and "URLTitle", then create this object "objURL" and set the values ​​and set button.datacontext = objURL. Then in the click event diine rb and obj and your text variables obj = rb.datacontext thetitle = obj.urltitle theURL = obj.urltext

0
source

Source: https://habr.com/ru/post/1703497/


All Articles