1
我有一个文本框,文本绑定到ViewModel中的属性。用户可以手动输入文本或从剪贴板粘贴。 我解析了用户输入的文本(我使用UpdateSourceTrigger = PropertyChanged),并通过换行符char分隔文本。文本框值从Viewmodel更改不反映在UI
问题:当用户点击输入时,一切工作正常。但是,当我尝试处理粘贴的文本时,只要我首先看到“\ n”,我会尝试将其分解为不同的字符串并清除文本框。在ViewModel中,文本被设置为string.empty,但不会反映在UI上。
代码有什么问题?我知道在自己的setter属性中编辑文本并不是很好的编程习惯,但是我该怎么做呢?
这里是代码片段:
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>
视图模型:
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;
}
}
感谢,
RDV
请问您的ViewModel执行INotifyPropertyChanged? – Dmihawk
您是否尝试在setter中的OnNewLineCommandEvent之后调用RaisePropertyChanged? –
是的,我的VM实现INotifyPropertyChanged-它被称为RaisePropertyChanged。是的,我在OnNewLineCommandEvent之后尝试调用RaisePropertyChanged,但它没有帮助 – RDV