[英]How to Two-way databind a TextBox's Text to a Dependency property
我正在嘗試雙向數據將 TextBox 的 Text 屬性綁定到父窗口的依賴屬性。
我已經在測試項目中將問題縮減為幾行,以嘗試讓綁定工作,並且已經搜索了好幾天。
從 Xaml 文件:
<StackPanel>
<TextBox Text="{Binding A, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Mode=TwoWay}" Margin="5"/>
<TextBox Text="{Binding B, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Mode=TwoWay}" Margin="5"/>
<Button Content="Random" Click="Button_Click" Margin="5"/>
</StackPanel>
並從 CS 文件:
public partial class MainWindow : Window
{
public static readonly DependencyProperty AProperty = DependencyProperty.Register("A", typeof(double), typeof(MainWindow));
public double A
{
get { return (double)GetValue(AProperty); }
set
{
SetValue(AProperty, value);
SetValue(BProperty, value);
}
}
public static readonly DependencyProperty BProperty = DependencyProperty.Register("B", typeof(double), typeof(MainWindow));
public double B
{
get { return (double)GetValue(BProperty); }
set
{
SetValue(AProperty, value);
SetValue(BProperty, value);
}
}
public MainWindow()
{
InitializeComponent();
A = 0d;
B = 1d;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
A = new Random().Next();
}
}
當窗口啟動時,兩個 TextBox 都顯示“1”(由於構造函數,正如預期的那樣)。 單擊該按鈕會導致兩個 TextBox 都更新為隨機數(也符合預期)。
但是更改任一 TextBox 中的文本不會更新綁定的依賴項屬性,因此不會更新其他 TextBox。
在這些操作期間沒有任何錯誤消息。
如果你想讓A
設置B
,反之亦然,你應該使用回調。 CLR 包裝器的 setter 應該只調用依賴屬性本身的SetValue
而不要做任何其他事情,例如:
public static readonly DependencyProperty AProperty = DependencyProperty.Register("A", typeof(double), typeof(MainWindow),
new PropertyMetadata(new PropertyChangedCallback(OnAChanged)));
public double A
{
get { return (double)GetValue(AProperty); }
set { SetValue(AProperty, value); }
}
private static void OnAChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MainWindow window = (MainWindow)d;
window.B = window.A;
}
public static readonly DependencyProperty BProperty = DependencyProperty.Register("B", typeof(double), typeof(MainWindow));
public double B
{
get { return (double)GetValue(BProperty); }
set { SetValue(BProperty, value); }
}
另請注意,如果您希望為每次擊鍵設置源屬性,則應將綁定的UpdateSourceTrigger
屬性設置為PropertyChanged
。 默認情況下,它們將在TextBox
失去焦點時設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.