I have a calculated property on my View that I need to bind to my ViewModel. I'm using WPF and it seems that there is no way to make a bindable property (Dependency Property) that is self calculating. I don't want to perform the calculations whenever the View's state changes because they are time intensive. I wan开发者_StackOverflowt to do the calculations whenever the ViewModel needs the result, i.e. when it closes.
Based on your comment above, I'd use a Converter
Your ViewModel would contain the encrypted data, and the binding to the View uses a Converter which converts it into something readable. When it's time to save the data back to the ViewModel, use the ConvertBack
method of the converter to encrypt the data again.
<TextBox Text="{Binding EncryptedAccountNumber,
Converter={StaticResource DecryptTextConverter}}" />
public class DecryptTextConverter: IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
// Implement decryption code here
return decryptedValue;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
// Implement encryption code here
return ecryptedValue;
}
}
If the Encryption code takes a while, set your UpdateSourceTrigger=Explicit
and manually trigger the source update when the Save button is clicked.
This is my solution. It works the same way as ICommand
but the view provides the delegate (CalculationDelegate
) and the view model calls CanExecute
and Execute
. Its not pure MVVM but it works.
public interface ICalculationProvider<TResult>
{
event EventHandler CanExecuteChanged;
Func<TResult> CalculationDelegate { get; set; }
bool CanExecute();
TResult Execute();
bool TryExecute(out TResult a_result);
}
I have marked Rachel's answer as correct, simply because what I am doing here is not pure MVVM.
精彩评论