65.9K
CodeProject 正在变化。 阅读更多。
Home

Silverlight 中 PropertyChanged 时的源更新

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.89/5 (13投票s)

2010年7月6日

CPOL

1分钟阅读

viewsIcon

38037

downloadIcon

282

一个简单的依赖属性,允许你在 PropertyChanged 事件发生时更新属性。

引言

你是否怀念 Silverlight 中 Binding 表达式中的 "UpdateSourceTrigger=PropertyChanged"? 我也是,而且我不太喜欢为了每次 TextBoxTextChange 而添加一个隐藏控件来改变焦点,所以我尝试为这个问题创建一个更优雅的解决方案。

背景

在 WPF 和 Silverlight 中,当我们创建一个 BindingExpression 时,你可以定义 BindingUpdateSourceTrigger 属性。 但是,它们之间存在巨大差异,Silverlight 只有 Default 模式 (LostFocus) 和 Explicit,因此我们缺少 PropertyChanged,在某些情况下,这会使我们的生活更加轻松。

Using the Code

代码非常简单。它只有一个 AttachedProperty,它将为你处理 TextChanged 事件,并在 TextPropertyBindingExpression 存在时更新 BindingSource

这仅在 TextBox 中实现,因为对于其他输入控件来说,LostFocus 已经可以完美工作了(例如 ComboBoxCheckBoxRadioButton),所以没有必要更改它们。

因此,我们定义一个 AttachedProperty,这对于任何 Silverlight 开发者来说都不应该是一个问题。

public static bool GetUpdateOnPropertyChanged(DependencyObject obj)
{
    return (bool)obj.GetValue(UpdateOnPropertyChangedProperty);
}

public static void SetUpdateOnPropertyChanged(DependencyObject obj, bool value)
{
    obj.SetValue(UpdateOnPropertyChangedProperty, value);
}

public static readonly DependencyProperty UpdateOnPropertyChangedProperty =
    DependencyProperty.RegisterAttached(
        "UpdateOnPropertyChanged",
        typeof(bool),
        typeof(UpdateSourceManager),
        new PropertyMetadata(
            new PropertyChangedCallback(
                UpdateOnPropertyChangedPropertyCallback)));

然后我们定义 UpdateOnPropertyChangedPropertyCallback

static void UpdateOnPropertyChangedPropertyCallback(
    DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    if (sender is TextBox)
    {
        TextBox txt = sender as TextBox;
        txt.TextChanged += new TextChangedEventHandler(txt_TextChanged);
    }
}

static void txt_TextChanged(object sender, TextChangedEventArgs e)
{
    TextBox txt = sender as TextBox;

    var bindingExpression = txt.GetBindingExpression(TextBox.TextProperty);
    if (bindingExpression != null)
    {
        bindingExpression.UpdateSource();
    }
}

然后,为了使用它,只需将适当的 XML 命名空间添加到你的 UserControl 中,如下所示

<UserControl x:class="UpdateSourceTrigger.MainPage"
    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="clr-namespace:UpdateSourceTrigger" 
    mc:ignorable="d">

最后,将 Attached Property 添加到 TextBox 中,如下所示

<TextBox 
    Text="{Binding Context.FirstName, Mode=TwoWay}" 
    Grid.Column="1" 
    Grid.Row="0" 
    Margin="5" 
    local:UpdateSourceManager.UpdateOnPropertyChanged="True"
    />

结束

希望这能让你的事情变得更容易,就像对我一样。

© . All rights reserved.