问题
I have a textbox, text is bound to a property in ViewModel. User can either manually enter the text or paste it from clipboard. I parse the text (I use UpdateSourceTrigger=PropertyChanged) entered by the user and split the text by newline char.
Problem: When user hits enter, everything works fine. But when I try to process the pasted text, as soon as I see first "\n", I try to break it into different strings and clear the textbox. In ViewModel, text is set to string.empty, but it is not reflected on the UI.
What is wrong in the code? I understand that editing the text in its own setter property is not good coding practice, but how can I do it otherwise?
Here is the code snippet:
XAML
<TextBox AcceptsReturn="True" VerticalAlignment="Stretch" BorderBrush="Transparent"
Text="{Binding TextBoxData, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding OnNewLineCommand}"/>
</TextBox.InputBindings>
</TextBox>
ViewModel:
public string TextBoxData
{
get
{
return _textBoxData;
}
set
{
_textBoxData = value;
RaisePropertyChanged("TextBoxData");
if(_textBoxData != null && _textBoxData.Contains("\n"))
{
OnNewLineCommandEvent(null);
}
}
}
public DelegateCommand<string> OnNewLineCommand
{
get
{
if (_onNewLineCommand == null)
{
_onNewLineCommand = new DelegateCommand<string>(OnNewLineCommandEvent);
}
return _onNewLineCommand;
}
}
private void OnNewLineCommandEvent(string obj)
{
if (_textBoxData != null && _textBoxData.Length > 0)
{
List<string> tbVals = _textBoxData.Split('\n').ToList();
foreach (string str in tbVals)
{
ListBoxItems.Add(new UnitData(str.Trim()));
}
TextBoxData = string.Empty;
}
}
Thanks,
RDV
回答1:
I figured out the issue. If I try to modify textbox value within its setter and value is not changed, it is not reflected on the UI. Below might help explain this better:
- Initially, when the UI starts textbox value in VM is set to "ABC".
- User changes this value to "XYZ" from the UI.
- In the VM setter, programmer checks if textbox value is "XYZ", then change it back to "ABC" --> This was failing in my case. The value of textbox in VM was changed to "ABC" but UI would still show "XYZ".
Solution: In VM, instead of setting value back to "ABC" set it to "ABC " (Notice the additional space) -> this will change the UI value.
Updated VM Code:
private bool _isTextValChanged = false;
private void OnNewLineCommandEvent(string obj)
{
if (_textBoxData != null && _textBoxData.Length > 0)
{
List<string> tbVals = _textBoxData.Split('\n').ToList();
foreach (string str in tbVals)
{
ListBoxItems.Add(new UnitData(str.Trim()));
}
//This will toggle textbox value and updated value will be reflected on the UI.
if (_isTextValChanged)
TextBoxData = " ";
else
TextBoxData = string.Empty;
_isTextValChanged = !_isTextValChanged;
}
}
Thanks,
RDV
来源:https://stackoverflow.com/questions/42679395/textbox-value-changed-from-viewmodel-not-reflected-on-ui