[英]Binding two textBoxes using MVVM Light
我有兩個並排的文本框, InputInches
和InputMillimeters
,我想要做的是英寸到毫米的轉換,類似於Goolge轉換的工作方式。 我想發生的是,當用戶開始在第一個文本框中輸入InputInches
,結果將顯示在第二個文本框中(InputMillimeters),反之亦然,如果用戶開始在第二個文本框中鍵入內容,則結果將是顯示在第一個文本框中。
以下代碼可以很好地完成我想要的英寸到毫米的轉換,但是如果我取消注釋convertMillimetersToInches()
方法中的代碼,則會出現錯誤。
關於如何使用MVVM Light進行這種類型的綁定的任何建議?
XAML:
<TextBox x:Name="textBox1"
Text="{Binding InputInches,UpdateSourceTrigger=PropertyChanged}"/>
<TextBox x:Name="textBox2"
Text="{Binding InputMillimeters,UpdateSourceTrigger=PropertyChanged}"/>
ViewModel:
namespace MyApp.ViewModel
{
public class ConversionViewModel : ViewModelBase
{
private string _inputInches;
private string _inputInchesTrimmed;
private string _inputMillimeters;
private string _inputMillimetersTrimmed;
public ConversionViewModel()
{
}
public string InputInches
{
get { return _inputInches; }
set {
_inputInches = value;
_inputInchesTrimmed = value.Trim();
RaisePropertyChanged();
if (_inputInchesTrimmed == "") {
_inputInchesTrimmed = "0";
}
convertInchesToMillimeters();
}
}
public string InputMillimeters
{
get { return _inputMillimeters; }
set {
_inputMillimeters = value;
_inputMillimetersTrimmed = value.Trim();
RaisePropertyChanged();
if (_inputMillimetersTrimmed == "") {
_inputMillimetersTrimmed = "0";
}
convertMillimetersToInches();
}
}
/// CONVERSION METHODS
private void convertInchesToMillimeters()
{
double millimeters = Convert.ToDouble(_inputInchesTrimmed) * 25.4;
InputMillimeters = Convert.ToString(millimeters);
}
private void convertMillimetersToInches()
{
//double inches = Convert.ToDouble(_inputInchesTrimmed) / 25.4;
//InputInches = Convert.ToString(inches);
}
}
}
錯誤信息:
確保您沒有無限循環或無限遞歸
簡單的答案:檢查您的方法在設置值之前是否相等(與其他方法重復):
private void convertInchesToMillimeters()
{
string millimeters = (Convert.ToDouble(_inputInchesTrimmed) * 25.4).ToString();
if(millimeters != InputMillimeters) InputMillimeters = millimeters;
}
更復雜的答案。 僅使用一個屬性並實現兩個wpf轉換器(請參閱https://www.wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/ )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.