亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

綁定到 UserControl 的屬性不起作用

綁定到 UserControl 的屬性不起作用

C#
POPMUISE 2023-09-16 16:14:50
我有一個自定義文本框,我計劃將其包含在另一個用戶控件中,但是在為其設置綁定時,它根本沒有綁定。為了清楚起見,我簡化了代碼。我的自定義文本框:<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));



查看完整回答
反對 回復 2023-09-16
  • 1 回答
  • 0 關注
  • 145 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號