2011-08-28 183 views
-1

请解决我的问题,我的列表框不绑定,我不为什么:(列表框绑定问题

class TLocation 
{ 
    public string name; 
} 

主窗口:

<Window x:Class="WpfApplication5.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfApplication5" 
     Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"> 

    <Window.Resources> 
     <DataTemplate DataType="{x:Type local:TLocation}" x:Key="myTaskTemplate"> 
      <TextBlock Height="23" HorizontalAlignment="Left" Margin="1" Name="textBlock1" Text="{Binding Path=name, FallbackValue=name}" VerticalAlignment="Top" /> 
     </DataTemplate> 
    </Window.Resources> 

    <Grid> 
     <ListBox Height="131" HorizontalAlignment="Left" Margin="29,44,0,0" Name="listBox1" VerticalAlignment="Top" Width="200" ItemTemplate="{StaticResource myTaskTemplate}" /> 
    </Grid> 
</Window> 

主窗口代码:

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     List<TLocation> list = new List<TLocation>(); 

     TLocation temp = new TLocation(); 

     temp.name = "hi"; 

     list.Add(temp); 

     listBox1.ItemsSource = list; 
    } 
} 

回答

1

namefield,你只能绑定到公共properties虽然你可能也想实现0如果名称在运行时更改,则为。如果您是数据绑定的新手,请务必阅读the overview

例如

public class TLocation : INotifyPropertyChanged 
{ 
    private string _name = null; 
    public string Name 
    { 
     get { return _name; } 
     set 
     { 
      if (_name != value) 
      { 
       _name = value; 
       OnPropertyChanged("Name"); 
      } 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     if (this.PropertyChanged != null) 
     { 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

(绑定也区分senstitive和您的大写不继conventions,所以我在我的例子改变了它,这里的Binding.Path将需要Name

+0

但它不工作再次! listbox是空的 – ArMaN

+0

@ArMaN:你是否改变了绑定路径到'Name'?另外:** [有方法来调试绑定](http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/30/debugging-data-bindings-in-a-wpf-or-silverlight -application.aspx)**,告诉我你得到的错误(并将它们发布在未来的问题中)。 –

+0

tnx:D明白了:) – ArMaN