I can't Data Bind to a local variable in WPF/XAML

后端 未结 5 1652
无人及你
无人及你 2021-01-01 01:14

I want a textbox to display the value of a variable when I click it (an iteration of 1 to 100), I do not know what I am doing Wrong:

When I run the project nothing i

5条回答
  •  -上瘾入骨i
    2021-01-01 01:54

    Try this:

     public partial class MainWindow : Window, INotifyPropertyChanged
        {
            public MainWindow()
            {
                InitializeComponent();
                this.DataContext = this;
            }
    
            public string myText { get; set; }
    
            public void Button_Click_1(object sender, RoutedEventArgs e)
            {
                BackgroundWorker bw = new BackgroundWorker();
                bw.DoWork += delegate
                {
                    int i = 0;
                    for (i = 0; i < 100; i++)
                    {
                        System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke((Action)(() => { myText = i.ToString(); OnPropertyChanged("myText"); }));                    
                        Thread.Sleep(100);
                    }
                };
    
                bw.RunWorkerAsync();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected void OnPropertyChanged(string name)
            {
                PropertyChangedEventHandler handler = PropertyChanged;
                if (handler != null)
                {
                    handler(this, new PropertyChangedEventArgs(name));
                }
            }
        }
    

    XAML file:

      
                

提交回复
热议问题