无法在WPF/XAML中将数据绑定到本地变量

6

当我点击文本框时,希望它显示一个变量的值(从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();
            }
        }
    }
}

XAML:
<Window x:Class="dataBindingTest.MainWindow"
        Name="windowElement"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <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="Left" Height="106" Margin="270,95,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="187" Text= "{Binding myText, ElementName=windowElement}" />

    </Grid>
</Window>

你应该研究MVVM模式。WPF绑定对实现INotifyPropertyChanged接口的对象的属性具有响应性。像Mvvmlight(可在NuGet上获取)这样的MVVM框架可以很好地为ViewModels和RelayCommands提供一些易于使用的基类。 - Glenn Ferrie
5个回答

11

您当前的myText属性无法通知WPF绑定系统其值何时发生更改,因此TextBlock将不会更新。

如果您将其替换为依赖属性,则它会自动实现更改通知,并且对属性的更改将反映在TextBlock中。

因此,如果您用以下所有代码替换public string 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));

9

实现 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:

<TextBox Text="{Binding txt}"/>
<Button Click="Button_Click">yes</Button>

别忘了添加窗口的DataContext属性:

<Window ... DataContext="{Binding RelativeSource={RelativeSource Self}}"/>

3

试试这个:

 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 文件:

  <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>

1

你应该在你的“MainWindow”中实现INotifyPropertyChanged,这样你的“myTextBlock”就可以自动从你的数据中获取更改并更新。

所以你的“MainWindow”应该像这样:

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.....
}

这个可以在2020年最新的WPF .NET Core中工作。 - Nick Chan Abdullah

0

你需要让该属性告诉绑定它已经更新。标准的方法是通过:

  1. 实现 INotifyPropertyChanged 接口
  2. 将 myText 属性设为 DependencyProperty
  3. 另外一种可能不太常用的方法是手动引发事件,例如:
public void Button_Click_1(object sender, RoutedEventArgs e)
{
    myText = "Clicked";
    BindingOperations.GetBindingExpressionBase(myTextBox, TextBlock.TextProperty).UpdateTarget();
}

请注意,您的具有令人困惑的名称。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接