C# 我能';t数据绑定到WPF/XAML中的局部变量

C# 我能';t数据绑定到WPF/XAML中的局部变量,c#,wpf,xaml,data-binding,C#,Wpf,Xaml,Data Binding,我想要一个文本框,当我单击某个变量时显示它的值(1到100的迭代),我不知道我做错了什么: 运行项目时,文本框中不会显示任何内容 在文本框中显示变量的最佳方式是什么 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; u

我想要一个文本框,当我单击某个变量时显示它的值(1到100的迭代),我不知道我做错了什么:

运行项目时,文本框中不会显示任何内容

在文本框中显示变量的最佳方式是什么

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace dataBindingTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public string myText { get; set; }

        public void Button_Click_1(object sender, RoutedEventArgs e)
        {
            int i = 0;
            for (i = 0; i < 100; i++)
            {
                myText = i.ToString();
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
命名空间数据绑定测试
{
/// 
///MainWindow.xaml的交互逻辑
/// 
公共部分类主窗口:窗口
{
公共主窗口()
{
初始化组件();
}
公共字符串myText{get;set;}
公共无效按钮\u单击\u 1(对象发送者,路由目标)
{
int i=0;
对于(i=0;i<100;i++)
{
myText=i.ToString();
}
}
}
}
XAML:


您应该在“主窗口”中实现
INotifyPropertyChanged
,这样您的“myTextBlock”就可以自动从数据中提取更改并进行更新

因此,您的“主窗口”应该如下所示:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private string _myText;

    public string myText { 
      get{return _myText;}
      set{_myText = value;
         if(PropertyChanged!=null) PropertyChanged(this, new PropertyChangedEventArgs("myText")) ;
      }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    etc.....
}

您需要让属性告诉绑定它已更新。执行此操作的标准方法是:

  • 实施
  • 将myText属性设置为
  • 另一种可能不太常用的方法是手动引发事件,如下所示:

  • 请注意,您的
    TextBlock
    具有令人困惑的名称
    myTextBox
    当前的
    myText
    属性无法在其值更改时通知WPF绑定系统,因此不会更新
    TextBlock

    如果改为将其作为依赖项属性,它将自动实现更改通知,并且对该属性的更改将反映在
    TextBlock

    因此,如果将
    公共字符串myText{get;set;}
    替换为所有这些代码,它应该可以工作:

    public string myText
    {
        get { return (string)GetValue(myTextProperty); }
        set { SetValue(myTextProperty, value); }
    }
    
    // Using a DependencyProperty as the backing store for myText.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty myTextProperty =
        DependencyProperty.Register("myText", typeof(string), typeof(Window1), new PropertyMetadata(null));
    
    试试这个:

     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));
                }
            }
        }
    
    public分部类主窗口:窗口,INotifyPropertyChanged
    {
    公共主窗口()
    {
    初始化组件();
    this.DataContext=this;
    }
    公共字符串myText{get;set;}
    公共无效按钮\u单击\u 1(对象发送者,路由目标)
    {
    BackgroundWorker bw=新的BackgroundWorker();
    bw.DoWork+=委托
    {
    int i=0;
    对于(i=0;i<100;i++)
    {
    System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke((操作)(()=>{myText=i.ToString();OnPropertyChanged(“myText”);});
    睡眠(100);
    }
    };
    RunWorkerAsync();
    }
    公共事件属性更改事件处理程序属性更改;
    受保护的void OnPropertyChanged(字符串名称)
    {
    PropertyChangedEventHandler处理程序=PropertyChanged;
    if(处理程序!=null)
    {
    处理程序(此,新PropertyChangedEventArgs(名称));
    }
    }
    }
    
    XAML文件:

      <Grid>
                <Button Content="Button" HorizontalAlignment="Left" Height="106" Margin="71,95,0,0" VerticalAlignment="Top" Width="125" Click="Button_Click_1"/>
                <TextBlock x:Name="myTextBox" 
                           HorizontalAlignment="Right" Height="106" Margin="0,95,46,0" 
                           TextWrapping="Wrap" VerticalAlignment="Top" Width="187" 
                           Text= "{Binding myText}" />
    
            </Grid>
    

    执行
    INotifyPropertyChanged

    public partial class MainWindow : Window, INotifyPropertyChanged
        {
            public MainWindow()
            {
                this.InitializeComponent();
            }
    
            private string _txt;
            public string txt
            {
                get
                {
                    return _txt;
                }
                set
                {
                    if (_txt != value)
                    {
                        _txt = value;
                        OnPropertyChanged("txt");
                    }
                }
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                txt = "changed text";
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }
    
    XAML:

    不要忘记添加窗口的DataContext属性:

    <Window ... DataContext="{Binding RelativeSource={RelativeSource Self}}"/>
    
    
    
    您应该研究MVVM模式。WPF绑定响应于实现INotifyPropertyChanged接口的对象上的属性。MVVM框架,如Mvvmlight(可在NuGet上获得)在为ViewModels和RelayCommands提供一些易于使用的基类方面做得很好。该基类在2020年最新的wpf.net内核中工作
    public partial class MainWindow : Window, INotifyPropertyChanged
        {
            public MainWindow()
            {
                this.InitializeComponent();
            }
    
            private string _txt;
            public string txt
            {
                get
                {
                    return _txt;
                }
                set
                {
                    if (_txt != value)
                    {
                        _txt = value;
                        OnPropertyChanged("txt");
                    }
                }
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                txt = "changed text";
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }
    
    <TextBox Text="{Binding txt}"/>
    <Button Click="Button_Click">yes</Button>
    
    <Window ... DataContext="{Binding RelativeSource={RelativeSource Self}}"/>