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

时间:2012-12-06 08:12:45

标签: 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>

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));
}

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

2 个答案:

答案 0 :(得分: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);
        }

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

有关回调的详情,请参阅Dependency Property Callbacks and Validation

希望这有帮助。

答案 1 :(得分:3)

你不应该在这里使用DependencyProperty

您的TextBox的Text属性是DependencyProperty,并且是绑定的目标,您的用户名属性是来源,应该是DependencyProperty也是!它应该是一个普通的旧财产,可以引发NotifyPropertyChanged

您只需要:

private string _username;
public string Username
{
    get
    {
        return _username;
    }
    set
    {
        _username = value;
         NotifyPropertyChanged("Username");
    }
}

(旁白:在创作自己的控件时,只需要使用DependencyProperties。)