开发者

How to Validate binded WPF TextBoxes which is depend on each other's value and how to enable/disable Ok button according to Validation

I have two textboxes and two buttons on c# WPF windows application

Application have One variable that called Total Amount. one text box is for Discount Percen开发者_C百科tage and other one is for Discount Amount. if i changed discount amount then percentage should get reflected using DataBinding in WPF and viceversa(I Have that)

I want to validate both the textboxes 1). Discount should be in range MIN to MAX 2). Discount Amount should not be grater than Total Amount

and then Ok button will get Enable/disable according to Validation


I would recommend that you adopt the MVVM pattern (if you haven't already) and have your validation logic contained in the view model. Using this approach, you can either:

  • Expose an IsValid property on the view model and bind it to the button; the property getter would return the result of your validation logic
  • Expose an ICommand on the view model whose CanExecute method would return the result of your validation logic (recommended)

A quick example:

public class DiscountViewModel : ViewModel // Base class implements INotifyPropertyChanged
{
  // Define all of your view model properties, i.e., DiscountAmount, DiscountPercent, etc.

  ...

  // Define a command

  public ICommand OKCommand { get; }
}

Then in your XAML view, you would add the following binding:

<Button Command={Binding Path=OkCommand} Content="OK" />

Again, this is just a brief example that should help point you in the right direction. There are tons of great resources on the MVVM pattern available as well as resources for the WPF command pattern. Here is a good introductory resource that covers both: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx


For every Binding you define you can add a Converter. This can converter can be a single value converter, then you must implement the IValueConverter Interface. But I think you can solve your problem with a IMultiValueConverter. This Converter can be given much values, which can also get from Bindings. The Converter is getting the values from the Bindings, processing them with your logic and then giving it back to your property where you defined it. http://msdn.microsoft.com/en-us/library/system.windows.data.imultivalueconverter.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜