Six*_*ree 2 c# data-binding wpf
出于某种原因,我真的很挣扎.我是wpf的新手,我似乎无法找到理解这个简单问题所需的信息.
我试图将文本框绑定到一个字符串,即程序活动的输出.我为字符串创建了一个属性,但是当属性更改时,文本框不会.我有一个listview的问题,但创建了一个刷新listview的调度程序.
我必须忽略一些重点,因为我认为使用wpf的一个好处是不必手动更新控件.我希望有人能把我送到正确的方向.
在windowMain.xaml.cs中
private string debugLogText = "initial value";
public String debugLog {
get { return debugLogText; }
set { debugLogText = value; }
}
Run Code Online (Sandbox Code Playgroud)
在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}" />
Run Code Online (Sandbox Code Playgroud)
在你的课上实现INotifyPropertyChanged.如果您有许多需要此接口的类,我经常发现使用如下所示的基类很有帮助.
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 ) );
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您只需确保在属性值更改时引发PropertyChanged事件.例如:
public class Person : ObservableObject {
private string name;
public string Name {
get {
return name;
}
set {
if ( value != name ) {
name = value;
OnPropertyChanged("Name");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)