Jas*_*inn 34 c# silverlight windows-phone-7
有没有办法让Windows Phone 7中的TextBox更新Binding,因为用户键入每个字母而不是失去焦点?
像下面的WPF TextBox一样:
<TextBox Text="{Binding Path=TextProperty, UpdateSourceTrigger=PropertyChanged}"/>
Run Code Online (Sandbox Code Playgroud)
Pra*_*ian 51
WP7的Silverlight不支持您列出的语法.请执行以下操作:
<TextBox TextChanged="OnTextBoxTextChanged"
Text="{Binding MyText, Mode=TwoWay,
UpdateSourceTrigger=Explicit}" />
Run Code Online (Sandbox Code Playgroud)
UpdateSourceTrigger = Explicit这里是一个聪明的奖金.它是什么? 显式:仅在调用UpdateSource方法时更新绑定源.当用户离开时,它会为您节省一个额外的绑定集TextBox.
在C#中:
private void OnTextBoxTextChanged( object sender, TextChangedEventArgs e )
{
TextBox textBox = sender as TextBox;
// Update the binding source
BindingExpression bindingExpr = textBox.GetBindingExpression( TextBox.TextProperty );
bindingExpr.UpdateSource();
}
Run Code Online (Sandbox Code Playgroud)
Par*_*Joe 23
我喜欢使用附属物.以防万一你进入那些小虫子.
<toolkit:DataField Label="Name">
<TextBox Text="{Binding Product.Name, Mode=TwoWay}" c:BindingUtility.UpdateSourceOnChange="True"/>
</toolkit:DataField>
Run Code Online (Sandbox Code Playgroud)
然后是支持代码.
public class BindingUtility
{
public static bool GetUpdateSourceOnChange(DependencyObject d)
{
return (bool)d.GetValue(UpdateSourceOnChangeProperty);
}
public static void SetUpdateSourceOnChange(DependencyObject d, bool value)
{
d.SetValue(UpdateSourceOnChangeProperty, value);
}
// Using a DependencyProperty as the backing store for …
public static readonly DependencyProperty
UpdateSourceOnChangeProperty =
DependencyProperty.RegisterAttached(
"UpdateSourceOnChange",
typeof(bool),
typeof(BindingUtility),
new PropertyMetadata(false, OnPropertyChanged));
private static void OnPropertyChanged (DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var textBox = d as TextBox;
if (textBox == null)
return;
if ((bool)e.NewValue)
{
textBox.TextChanged += OnTextChanged;
}
else
{
textBox.TextChanged -= OnTextChanged;
}
}
static void OnTextChanged(object s, TextChangedEventArgs e)
{
var textBox = s as TextBox;
if (textBox == null)
return;
var bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty);
if (bindingExpression != null)
{
bindingExpression.UpdateSource();
}
}
}
Run Code Online (Sandbox Code Playgroud)
不是通过绑定语法,不是,但没有它很容易.您必须处理TextChanged事件并在绑定上调用UpdateSource.
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
((TextBox) sender).GetBindingExpression( TextBox.TextProperty ).UpdateSource();
}
Run Code Online (Sandbox Code Playgroud)
这可以非常容易地转换为附加行为.
| 归档时间: |
|
| 查看次数: |
16430 次 |
| 最近记录: |