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因为我正在创建自己的控件.
你永远不会达到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的输出窗口中看到属性的更改.
有关回调的更多信息,请阅读依赖属性回调和验证
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
9512 次 |
| 最近记录: |