Social Icons

twitter google plus linkedin rss feed

Pages

9.11.10

Changing the NewValue in the PropertyChangedCallback

I don't usually write about Silverlight, this is for two main reasons, first because there's a lot of information in a lot of blogs and second because I don't work that much with Silverlight so I don't find that much problems. It was perfect until I really knew it, same as many other things...


Lately I'm using a lot this technology so new to me and already outdated for Microsoft and doubts are arising i.e. the one in today's post.

I was creating a new button to add it to a DataGrid as a DataGridTemplateColumn and I needed to create a DependencyProperty to bind it, everything very straightforward so far, but in the last moment when I was seen myself victorious I found a problem. If the property (an URL in this case) is not valid, How can I change the NewValue in the PropertyChangedCallback?

The trick is to call SetValue, that doesn't trigger the event; otherwise we'll get an infinite loop. It'll be something like this:

public string CommentsURL
{
    get { return (string)GetValue(CommentsURLProperty); }
    set { SetValue(CommentsURLProperty, value); }
}

public static readonly DependencyProperty CommentsURLProperty =
    DependencyProperty.Register("CommentsURL", typeof(string), typeof(ButtonComments),
    new PropertyMetadata(new PropertyChangedCallback(ChangedURL)));

private static void ChangedURL(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    try
    {
        string url = e.NewValue.ToString().Split(',')[0];
        new Uri(url);
        d.SetValue(e.Property, url);

        (d as ButtonComments).IsEnabled = true;
    }
    catch
    {
        (d as ButtonComments).IsEnabled = false;
    }
}
Note the refinement of the code, always avoiding the exceptions before they occur.


In the end, if someone feels curious about the result, the wepbart ended like this:



"Intellectuals solve problems; geniuses prevent them."

No comments:

Post a Comment