2012-12-05 144 views
6

我想将文本框的文本绑定到我的类中的某个属性,但它不工作,我在后面的代码中编辑属性,但在文本框中看不到该字符串 这是类,我试图绑定的属性叫做songFolder。wpf文本框文本绑定

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> 

--------------最新情况: --------------- 我加入下一行到窗口的构造函数:

BrowseBox.DataContext=new song() 

虽然调试只见该属性为c挂但文本框中的文本不是。

+0

您的通知事件中有一个错误的属性:'NotifyPropertyChanged(“sPath”);'应该是'NotifyPropertyChanged(“songsFolder”)'。 – McGarnagle

+0

谢谢,我改变了它,但它仍然不起作用 – alostr

+1

如果你解释除了“不工作”之外的其他问题,它可能会帮助我们... – McGarnagle

回答

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 /出静态密钥)

后面的代码,窗口的构造函数中:

browseBox.DataContext = new song(); 

然后,更新的textBox发现到:

<TextBox Name="browseBox" Text="{Binding Path=songsFolder, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="0"></TextBox> 
+0

添加它,仍然无法正常工作。在后面的代码中,我打开文件夹浏览器对话框并根据所选路径更改songsFolder属性,但我在文本框 – alostr

+0

@ user1622986中未看到它已更新。设置窗口的dataContext(请参阅编辑) –

+0

Can' t做到这一点,我使用窗口dataContext将歌曲列表绑定到列表框。 – alostr