【问题标题】:WPF Simple TextBox Binding - Dependency Property Never TouchedWPF 简单文本框绑定 - 从未触及依赖属性
【发布时间】:2012-12-06 08:12:45
【问题描述】:

我有一个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,因为我正在创建自己的控件。

【问题讨论】:

  • 您不应该使用 DependencyProperty 作为绑定源!看我的回答...
  • 糟糕,我没有说清楚。我实际上是在创建自己的控件,所以它需要是一个依赖属性。

标签: wpf binding textbox dependency-properties


【解决方案1】:

你永远不会到达 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

希望这会有所帮助。

【讨论】:

  • 另见XAML Loading and Dependency Properties中的解释,“自定义依赖属性的含义”部分。
  • 谢谢!我知道我错过了什么。
  • 没办法!您不应该使用 DependencyProperty 作为绑定的来源 - 请参阅我的答案。
【解决方案2】:

你不应该在这里使用DependencyProperty

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

你只需要:

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

(顺便说一句:您只需要在编写自己的控件时使用 DependencyProperties。)

【讨论】:

    猜你喜欢
    • 2011-07-23
    • 2012-11-08
    • 2014-08-31
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多