Dependency Property is not updating my Usercontrol

前端 未结 1 979
既然无缘
既然无缘 2020-12-16 19:38

The line below works for the TextBox DP Text, where CellNo is a property of a class which derives from INotifyPropertychanged. So here when I change the Cel

1条回答
  •  不知归路
    2020-12-16 20:08

    This code

    
    

    is trying to bind against the Property CellNo of the UserControl. Add RelativeSource or ElementName and it'll work.

    
    
    
    

    You may also need to set the the DataContext of control to itself

    public control()
    {
        InitializeComponent();
        this.DataContext = this;
        //...
    }
    

    Update

    You can download a sample application of this here.

    Otherwise, here's my full sample code.

    MainWindow.xaml

    
        
            
                

    Mainwindow.xaml.cs

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            CellNo = "Hello";
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            CellNo = "Hi";
        }
        private string m_cellNo;
        public string CellNo
        {
            get
            {
                return m_cellNo;
            }
            set
            {
                m_cellNo = value;
                OnPropertyChanged("CellNo");
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

    control.xaml

    
        
            
        
    
    

    control.xaml.cs

    public partial class control : UserControl
    {
        public string CellValue
        {
            get { return (string)GetValue(CellValueProperty); }
            set { SetValue(CellValueProperty, value); }
        }
        // Using a DependencyProperty as the backing store for LimitValue.  This enables animation, styling, binding, etc...    
        public static readonly DependencyProperty CellValueProperty =
            DependencyProperty.Register("CellValue", typeof(string), typeof(control), new FrameworkPropertyMetadata
            {
                BindsTwoWayByDefault = true,
            });
        public control()
        {
            InitializeComponent();
            this.DataContext = this;
            CellValue = "Test";
        }
    }
    

    0 讨论(0)
提交回复
热议问题