【发布时间】:2017-03-18 08:02:10
【问题描述】:
使用 Mvvm 库、UWP、C#。
问题:如果视图模型中的值发生更改并且文本框专注于该时刻,则视图不会更新文本框的内容。可以更新没有获得焦点的文本框的 viewmodel 属性。
为了消除混淆:文本框 -> 有焦点 -> 输入内容 -> 传递给绑定属性 -> 属性集,更改值并调用 RaisePropertyChange。 -> 文本框不更新。
如果绑定到不同 TextBox 的属性在 ViewModel 中发生更改,并且以该属性为目标调用 RaisePropertyChanged,则该 TextBox 确实会更新。
不同之处似乎在于具有焦点的文本框不会在 RaisePropertyChanged 上更新。它确实在 wpf 中执行此操作。
下面的代码是一个示例,而不是实际的应用程序。它确实显示了问题,并且就像实际应用程序一样。添加连字符以更改输入。如果 RaisePropertyChanged 确实有效,则连字符会显示在编辑框中,但不会。
我的页面:
<Page x:Class="BindingTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BindingTest.VML"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
DataContext="{Binding MainViewModel, Source={StaticResource Locator}}" >
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="0,144,0,109">
<TextBox x:Name="textBox1"
Text="{Binding Item1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left"
Margin="10,137,0,0"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="340"/>
<TextBox x:Name="textBox2"
Text="{Binding Item2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left"
Margin="10,174,0,0"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="340"/>
</Grid>
我的视图模型:
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace BindingTest
{
public class MainViewModel:ViewModelBase
{
string _item1 = "";
string _item2 = "";
public string Item1 {
get
{
return _item1;
}
set
{
_item1 = value + "-";
RaisePropertyChanged("Item1");
}
}
public string Item2
{
get {
return _item2;
}
set
{
_item2 = value + "-";
RaisePropertyChanged("Item2");
}
}
}
}
如果将文本放入任一文本框中,则调用属性集,更改值,文本框中的值不会更新。
如果我在 textbox1 的 setter 中调用 textbox2 的 propertychanged,它将更新:
public string Item1 {
get
{
return _item1;
}
set
{
_item2 = value + "-";
RaisePropertyChanged("Item2");
}
}
就好像有焦点的文本框只要有焦点就不会更新它的内容。
【问题讨论】:
-
太多代词缺少明确的先行词!我不明白你的问题描述。请更加准确,以便完全清楚执行了哪些用户操作、确切发生了什么以及您所期望的。我无法从您的帖子中看出您是否在视图模型以某种方式更改时视图未更新或视图模型以某种方式更改时视图模型未更新或其他原因时遇到问题。也不清楚为什么 a) 您通过添加连字符来修改输入,以及 b) 为什么您在
Item1设置器中设置_item2。 -
我认为这种行为是故意的
-
@PeterDuniho 问题后,它说:如果视图模型中的值发生更改并且文本框专注于那一刻,则视图不会更新文本框的内容。如果在视图模型中绑定的值发生了变化,并且调用了 raisepropertychanged,则文本框中的值不会更新。