简体   繁体   中英

Can I change a dependency property as a direct result of updating the source object of the binding of that dependency property in C#/Silverlight?

I have a custom datepicker element in C#/Silverlight with a datetime property that is bound to a source property. When I change date through the datepicker, it updates the source property correctly, but occasionally, I need to set the source property immediately back to its previous value due to it being an invalid date and have that change reflect back to the UI. I am able to set the source object correctly, and then reset it correctly, but I cannot manage to change the datepicker back to its original date. Note I don't mean an invalid date in terms of the format being invalid, just basically that the date is already "taken".

I believe the problem is that I'm trying to set the dependency object on the custom datepicker while it's in the middle of firing its binding from the last set action. To clarify: the datepicker is changed in the UI, which updates the dependency object in the custom datepicker, which fires a binding, which updates the source property, which causes the source property to set itself back to its previous value, which fails to set the dependency object again due to it still being in the middle of being set to the value the user picked in the UI.

Can a dependency object ever be set to something new as part of the chain of events caused by setting it? Is there any way to either implement this correctly, or else somehow workaround this issue? Is there any chance I'm misdiagnosing my problem?

The custom datepicker element is basically a standard datepicker wrapped with a few other UI elements, but I believe I would have the same issue if it were just the standard datepicker.

You could try using Dispatcher.BeginInvoke() to delay the execution of the code fragment that readjusts the source property:

Deployment.Current.Dispatcher.BeginInvoke(() =>
{
    sourceProperty = newValue;
});

Also, you might want to consider using the built-in capabilities of data validation instead of the abovementioned approach.

You can use something like this (in the view model):

public DateTime Date
{
    get { return _date; }
    set
    {
        if (value [is _not_in_range_])
            throw new Exception("Value is not in range");
        _date = value;
    }
}

Example: http://msdn.microsoft.com/en-us/library/cc278072(VS.95).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM