我正在尝试将文本框的文本绑定到我的类中的属性,并且它无法正常工作,我在后面的代码中编辑属性但是我没有看到文本框中的字符串 这是类,我试图绑定的属性叫做songFolder。
public class song : INotifyPropertyChanged
{
public string title {get; set; }
public string artist { get; set; }
public string path { get; set; }
public static string folder;
public string songsFolder { get { return folder; } set { folder = value; NotifyPropertyChanged("songsFolder"); } }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public song()
{
}
public song(string title, string artist, string path)
{
this.title = title;
this.artist = artist;
this.path = path;
}
}
和xaml,包含我要绑定的资源和文本框
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Song Filler" Height="455" Width="525">
<Window.Resources>
<local:song x:Key="song"/>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<TextBox Name="browseBox" Text="{Binding Source={StaticResource ResourceKey=song}, Path=songsFolder, Mode=TwoWay}" Grid.Column="0"></TextBox>
<Button Grid.Column="1" Width="auto" Click="Browse">browse</Button>
</Grid>
-------------- ----------------更新 我在窗口的ctor中添加了下一行:
BrowseBox.DataContext=new song()
在调试时我发现属性正在改变,但文本框中的文本不是。
答案 0 :(得分:2)
传递给NotifyPropertyChanged事件的字符串应该与属性本身的名称相同。
public string songsFolder
{
get
{
return folder;
}
set
{
folder = value;
NotifyPropertyChanged("songsFolder");
}
}
此外,
尝试将UpdateSourceTrigger =“PropertyChanged”添加到textBox的绑定
<TextBox Name="browseBox" Text="{Binding Source={StaticResource ResourceKey=song}, Path=songsFolder, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="0"></TextBox>
编辑:可能没有正确设置DataContext。您也可以尝试这种方法(W / out a static Key)
后面的代码,在窗口的Ctor中:
browseBox.DataContext = new song();
然后,将textBox发现更新为:
<TextBox Name="browseBox" Text="{Binding Path=songsFolder, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="0"></TextBox>