C# 数据绑定don';他似乎没有恢复精神
出于某种原因,我真的很挣扎。我是wpf的新手,似乎找不到理解这个简单问题所需的信息 我试图将一个文本框绑定到一个字符串,即程序活动的输出。我为字符串创建了一个属性,但当属性更改时,文本框不会更改。我在listview中遇到了这个问题,但创建了一个刷新listview的调度程序 我肯定错过了一些要点,因为我认为使用wpf的一个好处是不必手动更新控件。我希望有人能把我带向正确的方向 在windowMain.xaml.cs中C# 数据绑定don';他似乎没有恢复精神,c#,wpf,data-binding,C#,Wpf,Data Binding,出于某种原因,我真的很挣扎。我是wpf的新手,似乎找不到理解这个简单问题所需的信息 我试图将一个文本框绑定到一个字符串,即程序活动的输出。我为字符串创建了一个属性,但当属性更改时,文本框不会更改。我在listview中遇到了这个问题,但创建了一个刷新listview的调度程序 我肯定错过了一些要点,因为我认为使用wpf的一个好处是不必手动更新控件。我希望有人能把我带向正确的方向 在windowMain.xaml.cs中 private string debugLogText = "initial
private string debugLogText = "initial value";
public String debugLog {
get { return debugLogText; }
set { debugLogText = value; }
}
在windowMain.xaml中
x:Name="wndowMain"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
<TextBox Name="txtDebug" Text="{Binding ElementName=wndowMain, Path=debugLog}" />
x:Name=“wndowMain”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml"
DataContext=“{Binding RelativeSource={RelativeSource Self}}”
在类上实现InotifyProperty更改。如果有很多类需要这个接口,我经常发现使用下面这样的基类很有帮助
public abstract class ObservableObject : INotifyPropertyChanged
{
protected ObservableObject( )
{
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged( PropertyChangedEventArgs e )
{
var handler = PropertyChanged;
if ( handler != null ) {
handler( this, e );
}
}
protected void OnPropertyChanged( string propertyName )
{
OnPropertyChanged( new PropertyChangedEventArgs( propertyName ) );
}
}
然后,只要确保在属性值更改时引发PropertyChanged事件。例如:
public class Person : ObservableObject {
private string name;
public string Name {
get {
return name;
}
set {
if ( value != name ) {
name = value;
OnPropertyChanged("Name");
}
}
}
}
为什么要使用var handler=PropertyChanged;?线程安全?是的,这只是我养成的习惯。即使你不太可能从不同的线程中提升/订阅它,但它并没有太大的危害,它已经成为一种反射。其他人已经表明,可以通过初始化事件来消除检查,例如:public event PropertyChangedEventHandler PropertyChanged=delegate{};但它不仅速度慢,而且感觉被黑客攻击了。:)你是{}真的;然后,问题是,在每次属性更改时,您都要为委托调用付费,即使没有人在寻找信息-这(可能)是对上述内容的有用补充:受保护的void SetField(ref T field,T value,string propertyName){if(!EqualityComparer.Default.Equals(field,value)){field=value;OnPropertyChanged(propertyName);}-然后您可以使用(在集合中)设置字段(参考名称,值,“名称”);等等,很好!这是在基类中进行的。:)