我有一個自定義文本框,我計劃將其包含在另一個用戶控件中,但是在為其設置綁定時,它根本沒有綁定。為了清楚起見,我簡化了代碼。我的自定義文本框:<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}"> <TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" /></UserControl>partial class CustomTextBox : UserControl { public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public static readonly DependencyProperty TextProperty = DependencyProperty.Register( "Text", typeof(string), typeof(CustomTextBox), new PropertyMetadata(String.Empty));}此綁定按預期工作。當CustomTextBox在另一個用戶控件或窗口中使用時,我可以按預期訪問該屬性。以下代碼塊描述了使用的 UserControlCustomTextBox以及具有我想要綁定到的屬性的相應 ViewModel Text。<UserControl> <UserControl.DataContext> <vm:MyViewModel /> </UserControl.DataContext> <local:CustomTextBox Text="{Binding FooBar, UpdateSourceTrigger=PropertyChanged}" /></UserControl>public class MyViewModel : INotifyPropertyChanged{ private string _fooBar; public string FooBar { get { return _fooBar = (_fooBar ?? ""); } set { _fooBar = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged;}當我想將Text屬性綁定到另一個 UserControl 中的 ViewModel 時,我的問題就發生了,它只是不起作用。在本例中,我嘗試將Text屬性綁定到類FooBar上的屬性MyViewModel,但是對Text屬性的更改不會反映在FooBar屬性上,反之亦然。但是,當我將鼠標懸停在 XAML 視圖中的綁定上時,它會顯示屬性的類型,因此我并沒有完全看出這里出了什么問題。我最好的猜測是它與訪問同一屬性的兩個綁定有關。
1 回答

天涯盡頭無女友
TA貢獻1831條經驗 獲得超9個贊
修改 DP 注冊以包含FrameworkPropertyMetadataOptions.BindsTwoWayByDefault選項
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(CustomTextBox),
new FrameworkPropertyMetadata(String.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
- 1 回答
- 0 關注
- 145 瀏覽
添加回答
舉報
0/150
提交
取消