文本框MVVM数据绑定
我正在编写WPF计算器应用程序。在此应用程序中,我具有TextBox来根据OnWindowKeyDown事件获取和设置输入(输入插入/验证并作为用户类型返回到TextBox)。
I'm writing a WPF calculator app. In this application I have TextBox that get and set the input according to the OnWindowKeyDown event (input insert/validated and returned to the TextBox as the user type).
如果用户键入:
3-> validate == true--> print to TextBox '3'
y-> validate == false -> ignore
3-> validate == true --> print to TeextBox "33"
我想按字符获取输入字符(我有一个状态模式类,它对添加的每个char做出反应),但是我需要将结果作为字符串返回。
I want to get the input char by char (I have a State Pattern class that react to each char added), but I need to return the result as a string.
如何使用MVVM将数据与textBox相互传输?设计?
How can I transfer my data from and to the textBox, with the MVVM design?
应该足以绑定文本将
TextBox
的code>属性更改为 ViewModel
的属性。
It should be enough to bind a Text
property of TextBox
to ViewModel
's property.
例如:
//ViewModel
public class MyViewModel : INotifyPropertyChanged
{
private string textBoxText = string.Empty;
public string TextBoxText
{
get {return textBoxText;}
set {
textBoxText = value;
OnPropertyChanged("TextBoxText "..);
}
}
}
绑定 MyViewModel
到 Form
, TextBox DataContext
/ code>或其他...简而言之,使其以某种方式可用于您的 TextBox
。
Bind MyViewModel
to a DataContext
of your Form
, TextBox
or whatever... in short make it available to your TextBox
in some way.
定义一个转换器
,每 次调用该方法的时间 TextBox
集的> Text 属性。
Define a Converter
whom methods will be invoked every time Text
property of TextBox
set.
public class TextContenyConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// validate input and return appropriate value
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
绑定到 XAML
考虑到 DataContext
是类型 MyViewModel
其中, TextContenyConverterObject
是类型为 TextContenyConverter
的对象>定义为静态资源。
where TextContenyConverterObject
is an object of type TextContenyConverter
defined like a static resource.
这只是一个例子。
这是对 ValueConverters
。