2014-12-04 72 views
0

我是wpf的初學者。在我的項目之一,我有一個frmField類波紋管:將類成員綁定到列表框

public class frmFields 
{ 
    public bool succelssfulEnd = true; 
    public string fileName; 
    public List<string> errList = new List<string>(); 
} 

和列表

<ListBox Name="LSTErrors" Grid.Row="11" Grid.Column="1" Grid.ColumnSpan="2" ItemsSource ="{Binding}" SelectionChanged="LSTErrors_SelectionChanged" /> 

我需要errList綁定到上述列表框以這樣的方式,在列表的任何變化反映在ListBox上。

有人指導我嗎?

+0

如果你可以看到VB.Net那麼我以前[這裏的答案](http://stackoverflow.com/a/8549710/109702),這將有助於。不要忘記設置窗口的DataContext,然後你的ListBox會自動繼承該DataContext(除非你先將它重置在視覺樹中的某處)。並使用屬性或依賴項屬性,而不是字段。 – slugster 2014-12-04 11:36:07

回答

0

您需要一個ObservableCollection才能在每次更改UI時刷新UI。

public class frmFields 
{ 
    public bool succelssfulEnd = true; 
    public string fileName; 

    private ObservableCollection<String> _errList = new ObservableCollection<String>(); 
    public ObservableCollection<String> ErrList { 
     get {return _errList;} 
     set { 
      _errList = value; 
      //your property changed if you need one 
     } 
    } 
} 

請注意,您只能綁定到屬性或DependencyProperty,而不是像您嘗試的簡單公共變量。

在你的構造函數,你需要添加:

this.DataContext = this; 

或在您的XAML:

DataContext="{Binding RelativeSource={RelativeSource self}}" 

在你的根元素。然後綁定的ItemsSource這樣的:

<ListBox ItemsSource="{Binding ErrList, Mode=OneWay}"> 
    ... 
</ListBox>