我可以向您建议一种完成此任务的方法,这在Silverlight的其他版本(WPF 和primis 中的 Windows Phone )上会更容易......
如您所见,BindingExpression
没有Windows RT/Store 应用程序!...
实现此代码,与您的MVVM 模式兼容...
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace YourProject
{
public static class TextBoxEx
{
public static string GetRealTimeText(TextBox obj)
{
return (string)obj.GetValue(RealTimeTextProperty);
}
public static void SetRealTimeText(TextBox obj, string value)
{
obj.SetValue(RealTimeTextProperty, value);
}
public static readonly DependencyProperty RealTimeTextProperty = DependencyProperty.RegisterAttached("RealTimeText", typeof(string), typeof(TextBoxEx), null);
public static bool GetIsAutoUpdate(TextBox obj)
{
return (bool)obj.GetValue(IsAutoUpdateProperty);
}
public static void SetIsAutoUpdate(TextBox obj, bool value)
{
obj.SetValue(IsAutoUpdateProperty, value);
}
public static readonly DependencyProperty IsAutoUpdateProperty =
DependencyProperty.RegisterAttached("IsAutoUpdate", typeof(bool), typeof(TextBoxEx), new PropertyMetadata(false, OnIsAutoUpdateChanged));
private static void OnIsAutoUpdateChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var textbox = (TextBox)sender;
if ((bool)e.NewValue)
textbox.TextChanged += textbox_TextChanged;
else
textbox.TextChanged -= textbox_TextChanged;
}
private static void textbox_TextChanged(object sender, TextChangedEventArgs e)
{
var textbox = (TextBox)sender;
textbox.SetValue(TextBoxEx.RealTimeTextProperty, textbox.Text);
}
}
}
...然后只需在您的 XAML 中使用它,并带有一个小技巧(双重绑定),如下所示...
1)声明新的“实用程序”类:
<common:LayoutAwarePage x:Name="pageRoot"
x:Class="YourProject.YourPage"
DataContext="{Binding Path=DefaultViewModel, RelativeSource={RelativeSource Self}}"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="YourProject"
...
xmlns:extra="using:YourProject.YourNameSpace"
mc:Ignorable="d">
2)在您的控件中实施:
<TextBox extra:TextBoxEx.IsAutoUpdate="True"
extra:TextBoxEx.RealTimeText="{Binding Path=YourTextProperty, Mode=TwoWay}">
<TextBox.Text>
<Binding Path="YourTextProperty"
Mode="OneWay" />
</TextBox.Text>
</TextBox>
这对我来说很好,我希望可以帮助你!