2017-04-19 34 views
-1

我正在使用WPF和C#。 我有一個自定義控件,其中包含一個TextBox。自定義控件具有一個依賴屬性FilterText。我的ViewModel的CurrentText屬性綁定到我的控件的FilterText屬性。將依賴屬性綁定到DependencyProperty只能在一個方向上工作

目標是當TextBox的Text-property發生變化時,這會更新我的ViewModel的CurrentText屬性。

問題:更新TextBox的文本不會更新我的控件的FilterText DP。但是,更改FilterText屬性會更新TextBox的文本。

自定義用戶控件:

<UserControl x:Name="generalQuickSearch" (..)> 
(..) 
    <TextBox Text="{Binding FilterText, ElementName=generalQuickSearch, Mode=TwoWay}"/> 
(..) 
</UserControl> 

依賴屬性的用戶控件的代碼隱藏:

public static readonly DependencyProperty FilterTextProperty = DependencyProperty.Register("FilterText", typeof(string), typeof(GeneralQuickSearch)); 

在我看來,使用自定義控制:

<controls:GeneralQuickSearch FilterText="{Binding CurrentText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 

使用史努比,當我在文本框中輸入文本時:

01我generalQuickSearch控制

Text property of the TextBox

FilterText屬性:

FilterText property on GeneralQuickSearch control

我不明白爲什麼這是行不通的。任何幫助表示讚賞。

回答

0

發現問題和解決方案:TextBox的Text屬性默認只在LostFocus處更新。這可以通過添加這與結合被改變:

UpdateSourceTrigger=PropertyChanged 

來源:https://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

默認爲默認,它返回目標依賴項屬性的默認UpdateSourceTrigger值。但是,大多數依賴屬性的默認值是PropertyChanged,而Text屬性的默認值是LostFocus。

相關問題