嗨,我想通過后面的代碼設定文本框的 Text 屬性。目前我確實使用 XAML:
<TextBox x:Name="txtFilter" Text="{Binding FiltroFunzioni, Mode=OneWayToSource}" Grid.Row="0" />
作為測驗,我這樣做了:
Binding b = new Binding();
b.Mode = BindingMode.OneWayToSource;
b.Path = new PropertyPath("Text"); //??
b.Source = PageViewModel.FiltroFunzioni;
BindingOperations.SetBinding(txtFilter, TextBlock.TextProperty, b);
變數“FiltroFunzioni”是一個定義為屬性的字串:
private string _filtroFunzioni = "";
public string FiltroFunzioni
{
get { return _filtroFunzioni; }
set
{
_filtroFunzioni = value;
RaisePropertyChanged("FiltroFunzioni");
_functionsView.Refresh();
}
}
基本上我不知道我應該將什么樣的值設定為 PropertyPath。有任何想法嗎?
uj5u.com熱心網友回復:
此處不需要 PropertyPath。如果你只是洗掉它,你的系結應該可以作業。
話雖如此,您應該盡可能在 XAML 中進行系結。
如果您的問題是更改為FiltroFunzioni不更新您的文本框,那是因為您的系結被明確宣告為 OneWayToSource:這意味著更改 UI 會更改源,但更改源不會更改 UI。如果這不是您想要的,請將模式設定為其他內容,例如“TwoWay” - 然后更改源會更改 UI,并且更改 UI 會更改源。
編輯:
如果您真的想從 ViewModel 系結而不是僅使用 XAML,則在通過 C# 系結時,由于某種原因,TwoWay 系結需要使用 Path。以下任一解決方案都有效:
b.Source = FiltroFunzioni;
b.Path = new PropertyPath(".");
b.Source = this;
b.Path = new PropertyPath("FiltroFunzioni");
請注意,對于 TwoWay 系結,您必須FiltroFunzioni通過TextBox.Text在 XAML 中設定屬性來初始化您的屬性,或者FiltroFunzioni在系結初始化之后進行設定。否則,WPF 將立即從 TextBox 中的(默認為空)文本覆寫它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/349818.html
下一篇:將文本框系結到wpf表單上的按鈕
