问题描述
好吧,我一直在打扰我的大脑,我错过了一些东西,我根本找不出什么。最终我试图设置数据绑定,所以我可以更新显示的值,但在我的生活中,它不起作用。XAML是:
< TextBox x:Name =textBoxHorizontalAlignment =Left
Height =37Margin = 85,38,0,0TextWrapping =Wrap
Text ={Binding Path = TBBind}VerticalAlignment =Top
Width =121/>
请注意,我有 {Binding Path = TBBind}
set。
后面的代码是:
System.ComponentModel;
使用System.Windows;
命名空间Databinding_Practice_2
{
///< summary>
/// MainWindow.xaml的交互逻辑
///< / summary>
public partial class MainWindow:Window,INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
TBBind =test;
}
私人字符串_tBBind;
public string TBBind
{
get {return _tBBind; }
set
{
if(value!= _tBBind)
{
_tBBind = value;
OnPropertyChanged(TBBind);
}
}
}
公共事件PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string property)
{
MessageBox.Show(OnPropertyChanged triggered);
if(PropertyChanged!= null)
{
PropertyChanged(this,new PropertyChangedEventArgs(property));
}
}
}
}
帮助呃,等等,帮助我任何人!
尝试:
public MainWindow()
{
InitializeComponent();
DataContext = this;
TBBind =test;
}
这里的区别设置关键的 DataContext
属性。这是您在这里实现的MVVM模式的基石。您应该考虑将View Model的责任分离为另一个类,然后将View的 DataContext
设置为该类的实例,但是您在此处使用的方法适用于简单的情况。
Okay I've been wracking my brain a lot about this one, I'm missing something, I just can't figure out what. Ultimately I'm trying to set databinding so I can update values to be shown on the fly, but for the life of me, it's not working.
The XAML is:
<TextBox x:Name="textBox" HorizontalAlignment="Left"
Height="37" Margin="85,38,0,0" TextWrapping="Wrap"
Text="{Binding Path=TBBind}" VerticalAlignment="Top"
Width="121" />
Note that I have the {Binding Path=TBBind}
set.
The code behind is:
using System.ComponentModel;
using System.Windows;
namespace Databinding_Practice_2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
TBBind = "test";
}
private string _tBBind;
public string TBBind
{
get { return _tBBind; }
set
{
if (value != _tBBind)
{
_tBBind = value;
OnPropertyChanged("TBBind");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string property)
{
MessageBox.Show("OnPropertyChanged triggered");
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
}
Help me obi-w.... oh wait, help me anyone!
Try:
public MainWindow()
{
InitializeComponent();
DataContext = this;
TBBind = "test";
}
The difference here sets the critical DataContext
property. This is the cornerstone of the MVVM pattern, which you are implementing here. You should consider separating the View Model responsibility into another class, and then setting the View's DataContext
to an instance of that class, but the approach you have taken here works for simple cases.
这篇关于C#XAML数据绑定在属性更改时无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!