WPF binding binding error message

OK, working on WPF (using MVVM) and faced with a question, I want to contribute. I have a simple class

as shown below (suppose I have IDataErrorInfo):

public class SimpleClassViewModel { DataModel Model {get;set;} public int Fee {get { return Model.Fee;} set { Model.Fee = value;}} } 

Then I try to bind it to xaml:

 <TextBox Text={Binding Fee, ValidatesOnDataErrors=true}/> 

when the user deletes the text, a data binding error occurs because he cannot convert string.empty to int. Well, the board is a required field, but since the data binding will not convert back, I cannot provide error information because my class is not updated. So, I have to do the following:

 public class SimpleClassViewModel { DataModel Model {get;set;} int? _Fee; public int? Fee { get { return _Fee;} set { _Fee = value;if (value.HasValue) { Model.Fee = value;} } } 
+4
source share
2 answers

This can be done using ValueConverter:

 using System.Windows.Data; namespace MyNameSpace { class IntToStringConverter:IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return ((int) value).ToString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { int result; var succes = int.TryParse((string) value,out result); return succes ? result : 0; } } } 

You reference it in XAML this way:

 <Window xmlns:local="clr-namespace:MyNameSpace"> <Window.Resources> <local:IntToStringConverter x:Key="IntConverter"/> </Window.Resources> <TextBox Text={Binding Fee, ValidatesOnDataErrors=true, Converter={StaticResource IntConverter}}/> </Window> 
+5
source

You can also take advantage of the fact that you are doing MVVM and changing the type of the Fee property to string . In the end, your virtual machine should provide a model that supports the view, and the view allows users to enter string . You can then provide a separate property that exposes the parsed board as an int . Thus, your conversion logic is directly in the Fee property, which simplifies reuse, debugging, and support.

+2
source

Source: https://habr.com/ru/post/1285922/


All Articles