Chain of DataBinding

Posted by Neir0 on Stack Overflow See other posts from Stack Overflow or by Neir0
Published on 2010-05-03T22:05:57Z Indexed on 2010/05/03 22:08 UTC
Read the original article Hit count: 433

Filed under:
|
|

Hello

I am trying to do follow DataBinding

Property -> DependencyProperty -> Property

But i have trouble. For example, We have simple class with two properties implements INotifyPropertyChanged:

public class MyClass : INotifyPropertyChanged
    {
        private string _num1;
        public string Num1
        {
            get { return _num1; }
            set
            {
                _num1 = value;
                OnPropertyChanged("Num1");
            }
        }

        private string _num2;
        public string Num2
        {
            get { return _num2; }
            set
            {
                _num2 = value;
                OnPropertyChanged("Num2");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string e)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(e));
        }
    }

And TextBlock declared in xaml:

<TextBlock Name="tb" FontSize="20" Foreground="Red" Text="qwerqwerwqer" />

Now lets trying to bind Num1 to tb.Text:

private MyClass _myClass = new MyClass();
        public MainWindow()
        {
            InitializeComponent();

            Binding binding1 = new Binding("Num1")
                                   {
                                       Source = _myClass, 
                                       Mode = BindingMode.OneWay
                                   };

            Binding binding2 = new Binding("Num2")
            {
                Source = _myClass,
                Mode = BindingMode.TwoWay
            };

            tb.SetBinding(TextBlock.TextProperty, binding1);

            //tb.SetBinding(TextBlock.TextProperty, binding2);


            var timer = new Timer(500) {Enabled = true,};

            timer.Elapsed += (sender, args) => _myClass.Num1 += "a";

            timer.Start();


        }

It works well. But if we uncomment this string

tb.SetBinding(TextBlock.TextProperty, binding2);

then TextBlock display nothing. DataBinding doesn't work! How can i to do what i want?

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf