问题
I want to extend a WPF button to store some extra data, in a similar way to the current "Tag" property. Are attached properties the way forward? The data I want to store will be a URL Link string, for example I would like to be able to do something like:
<Button Tag="BBC World News" URLLink="http://www.bbc.co.uk"/>
Can anyone help me to understand how to extend the Button?
Many thanks
Jay
回答1:
You can use an 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 like this:
<Button Tag="BBC World News" ButtonBehavior.UrlLink="http://www.bbc.co.uk" Click="btnArticleView"/>
And you click handler 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
}
回答2:
Define the attached property like this
public static readonly DependencyProperty UrlLinkProperty =
DependencyProperty.RegisterAttached("UrlLink",
typeof(String),
typeof(ButtonBehavior)
new FrameworkPropertyMetadata(null));
回答3:
I am not sure about your goal here. You dont need to extend the Button for storing two values. You can always set the Datacontext of the Button with custom data object which contains this two values. Can you explain more on your problem.
回答4:
Thanks for your response.
I have a listbox which has a complex custom data template. The template contains a button. When I click the button I want to send 2 strings which are "URL link" and "URL Title". So I am binding many values in my list box data template, and I want to pass two of them on Button click event. Code example:
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
}
and XAML:
<Button Tag="BBC World News" URLLink="http://www.bbc.co.uk" Click="btnArticleView"/>
Cheers
Jay
回答5:
I know this is an old post but...
you could always create a custom class "MyURL" with 2 properties "URLText" and "URLTitle" then create that object "objURL" and set the values and set the button.datacontext = objURL. Then in the click event difine rb and obj and your text variables obj = rb.datacontext theTitle = obj.urltitle theURL = obj.urltext
来源:https://stackoverflow.com/questions/565695/extending-wpf-button-to-store-data-in-a-new-property