[英]WPF binding to custom control (textbox) not working
我編寫了一個簡單的自定義控件,該控件繼承自文本框,並使用自定義輸入框輸入文本:
class TextTextbox : TextBox
{
public string InputBoxTitle { get; set; }
public string Input { get; set; }
public TextTextbox()
{
PreviewMouseDown += MyTextbox_MouseDown;
}
private void MyTextbox_MouseDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
TextBox tb = (TextBox)sender;
var dialog = new BFH.InputBox.InputBox(InputBoxTitle, Input);
dialog.ShowDialog();
if (!dialog.Canceled)
tb.Text = dialog.Input;
else
tb.Text = Input;
}
}
我在這樣的視圖中使用它:
<CustomControls:TextTextbox Text="{Binding Test}" InputBoxTitle="Titel" Input="Input"/>
在虛擬機中進行測試:
private string _test;
public string Test
{
get { return _test; }
set
{
if (_test == value)
return;
_test = value;
RaisePropertyChanged("Test");
}
}
但與Test
的綁定無效。 在視圖中,我看到文本框的文本確實發生了變化,但是我似乎沒有鏈接到VM的屬性。 我用MessageBox.Show(Test)
添加了一個按鈕,但它始終為空。 我在這里做錯了什么?
您需要將綁定的UpdateSourceTrigger
屬性設置為PropertyChanged
。 否則,在TextBox失去焦點之前,不會更新源屬性Test
。
<CustomControls:TextTextbox
Text="{Binding Test, UpdateSourceTrigger=PropertyChanged}" ... />
從MSDN上Binding.UpdateSourceTrigger
頁面上的“ 示例”部分:
TextBox.Text屬性的默認UpdateSourceTrigger值為LostFocus。 這意味着,如果應用程序具有帶數據綁定TextBox.Text屬性的TextBox,則在TextBox失去焦點之前(例如,當您單擊TextBox時),您在TextBox中鍵入的文本不會更新源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.