WPF简单TextBox绑定 - 从未触及依赖属性

jam*_*rom 2 wpf binding textbox dependency-properties

我有一个TextBox,我试图将它绑定到一个DependencyProperty.该物业永远不会在装载或我输入时触及TextBox.我错过了什么?

XAML

<UserControl:Class="TestBinding.UsernameBox"
        // removed xmlns stuff here for clarity>
    <Grid>
        <TextBox Height="23" Name="usernameTextBox" Text="{Binding Path=Username, ElementName=myWindow, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
    </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

C#

public partial class UsernameBox : UserControl
{
    public UsernameBox()
    {
        InitializeComponent();
    }

    public string Username
    {
        get
        {
            // Control never reaches here
            return (string)GetValue(UsernameProperty);
        }
        set
        {
            // Control never reaches here
            SetValue(UsernameProperty, value);
        }
    }

    public static readonly DependencyProperty UsernameProperty
        = DependencyProperty.Register("Username", typeof(string), typeof(MainWindow));
}
Run Code Online (Sandbox Code Playgroud)

编辑:我需要实现一个DependencyProperty因为我正在创建自己的控件.

Eug*_*rda 9

你永远不会达到setter因为它是依赖属性的CLR包装器,它被声明是从外部源设置的,比如mainWindow.Username = "myuserName";.当通过绑定设置属性并且您想要查看它是否已更改时,只需将PropertyMetadata声明添加到您的声明中PropertyChangedCallback,例如:

public static readonly DependencyProperty UsernameProperty =
            DependencyProperty.Register("Username", typeof(string), typeof(MainWindow), new UIPropertyMetadata(string.Empty, UsernamePropertyChangedCallback));

        private static void UsernamePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Debug.Print("OldValue: {0}", e.OldValue);
            Debug.Print("NewValue: {0}", e.NewValue);
        }
Run Code Online (Sandbox Code Playgroud)

使用此代码,您将在VS的输出窗口中看到属性的更改.

有关回调的更多信息,请阅读依赖属性回调和验证

希望这可以帮助.

  • 另请参阅[XAML加载和依赖关系属性](http://msdn.microsoft.com/en-us/library/bb613563.aspx)中的说明,"自定义依赖关系属性的含义"部分. (3认同)