【问题标题】:How to make custom Dependency Property can be changed in real time when binding in wpf?在wpf中绑定时如何使自定义的依赖属性可以实时更改?
【发布时间】:2013-03-26 03:25:33
【问题描述】:

当我们像这样将 textblock.Text 与 Textbox 的文本长度绑定时

<TextBox x:Name="txtName" Grid.Row="0" />
<TextBlock Text="{Binding ElementName=txtName, Path=Text.Length}" Grid.Row="1" />

Textblock 的文本会随着 txtName 的文本实时变化。 但是当我像这样在 WPF 用户控件中定义一个新的 DependencyProperty 时:

    //MyCustomUC.xaml.cs
    static FrameworkPropertyMetadata propertymetadata = new FrameworkPropertyMetadata("Comes as Default", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(MyCustom_PropertyChanged), new CoerceValueCallback(MyCustom_CoerceValue), false, UpdateSourceTrigger.PropertyChanged);

    public static readonly DependencyProperty MyCustomProperty = DependencyProperty.Register("MyCustom", typeof(string), typeof(MyCustomUC), propertymetadata, new ValidateValueCallback(MyCustom_Validate));

    public string MyCustom
    {
        get
        {
            return this.GetValue(MyCustomProperty) as string;
        }
        set
        {
            this.SetValue(MyCustomProperty, value);
        }
    }

并将其绑定到文本框

//MyCustomUC.xaml
<UserControl ... x:Name="ucs" ...>
<TextBox Text="{Binding ElementName=ucs, Path=MyCustom}"></TextBox>
</UserControl>

//MainWindow.xaml
<local:MyCustomUC x:Name="ucust" Grid.Row="0" />
<TextBox x:Name="tbChange" Text="{Binding ElementName=ucust, Path=MyCustom}" Grid.Row="1"/>

在文本框失去焦点之前,“MyCustom”似乎不会改变。当文本框中的文本实时更改时,如何更改它? 提前谢谢你。

【问题讨论】:

    标签: wpf binding real-time dependency-properties


    【解决方案1】:
    <TextBox x:Name="tbChange" Text="{Binding ElementName=ucust, Path=MyCustom, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1"/>
    

    【讨论】:

    • 谢谢。所以我发现TextBox默认失去焦点时会触发更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多