在使用 mvvm 时,如何在 Windows Phone 8 应用程序的文本框中键入文本时检测更改,但请注意我没有使用 mvvmlight。
我尝试使用交互。触发器,虽然每次我键入某些文本时都会触发事件,但绑定到控件的模型不会在我的视图模型中设置控件的 Text 属性。
我的视图模型有一个允许访问实际模型的属性,通常我会有:
<TextBox Text={Binding Person.Title, Mode=TwoWay}"
但为了测试,我刚刚直接在我的 ViewModel 中创建了一个 Title 属性,但行为相同。
我很确定 Text 属性已正确绑定,因为我在初始化视图时放置了断点并且确实被调用了。
这是我拥有的代码,每次键入时都会触发一个事件,但不幸的是,我的标题似乎从未设置过。
<TextBox Text="{Binding Title, Mode=TwoWay}" Grid.Row="1">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding TitleTextChanged, Mode=OneWay}" CommandParameter="{Binding}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
有什么想法吗?
谢谢。
更新:
更改的属性肯定是从我的视图模型中提出的,使用
public string Title
{
get { return this._title; }
set { if (this._title != value) this.SetProperty(ref this._title, value); }
}
但如前所述,我添加此属性只是为了测试属性更改事件,因为我通常会通过以下方式通过我的 ViewModel 访问我的模型对象:
public PersonModel CurrentPerson
{
get { return this._currentPerson; }
set { if (this._currentPerson != value) this.SetProperty(ref this._currentPerson, value);}
}
我希望这能澄清一些事情。
谢谢。
<TextBox Text="{Binding TextInViewModel, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"/>
一些想法...你提高财产改变吗?MVVM-light可以帮助您执行此操作,如果没有它,则需要手动执行此操作。
您可以发布您的财产的代码,但我冒昧地猜测这就是问题所在。
另外,您说您将视图绑定到更改视图模型的模型...这一切听起来都像汤...视图绑定到视图模型。视图模型充当模型和视图之间的桥梁(当然不应该知道您的视图,但它有助于您从模型中获得所需的内容)。
为了检测在文本框中键入文本时的变化,我使用了 Prism 中的行为。
在 xaml 中:
<TextBox Text="{Binding Path=Name, Mode=TwoWay}">
<i:Interaction.Behaviors>
<extensions:UpdateTextBindingOnPropertyChanged />
</i:Interaction.Behaviors>
</TextBox>
行为代码(UpdateTextBindingOnPropertyChangedBehavior.cs):
using System;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Interactivity;
namespace MyApp.Extensions
{
/// <summary>
/// Custom behavior that updates the source of a binding on a text box as the text changes.
/// </summary>
public class UpdateTextBindingOnPropertyChanged : Behavior<TextBox>
{
private BindingExpression _expression;
/// <summary>
/// Called after the behavior is attached to an AssociatedObject.
/// </summary>
/// <remarks>
/// Override this to hook up functionality to the AssociatedObject.
/// </remarks>
protected override void OnAttached()
{
base.OnAttached();
_expression = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
AssociatedObject.TextChanged += new TextChangedEventHandler(this.OnTextChanged);
}
/// <summary>
/// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred.
/// </summary>
/// <remarks>
/// Override this to unhook functionality from the AssociatedObject.
/// </remarks>
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.TextChanged -= new TextChangedEventHandler(this.OnTextChanged);
_expression = (BindingExpression) null;
}
private void OnTextChanged(object sender, EventArgs args)
{
_expression.UpdateSource();
}
}
}
您需要将 System.Windows.Interactivity.dll 添加到项目中。每次触发控件 TextChanged 事件时,此行为将调用绑定的属性资源库。效果很好(如果你不设置模式=双向)。