我有一个名为Paths
的列表,它存储字符串元素。在MainWindow中,我创建一个ItemControl来显示应该绑定到Paths
的字符串元素的文本框。例如,如果Paths
由两个字符串元素"Hello"
和"World"
组成,则主窗口应显示两个文本框,一个显示“ Hello”,一个显示“ World”,并且绑定应为在TwoWay中。那么我应该如何正确进行绑定工作?
备注:我知道我应该使用ObservableCollection并将其绑定到ItemControl的ItemSource,但是我不知道正确的方法。
主窗口
<ItemsControl ItemsSource="{Binding PathsCollection}">>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=?????, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
DataContext
public class SomeClass
{
private List<string> _paths;
public List<string> Paths
{
get {return _paths;}
set {_paths = value; }
}
public ObservableCollection<string> PathsCollection
{
get
{ // return what????
}
set
{
// set what????
}
}
}
答案 0 :(得分:-1)
您是对的。您应该使用ObservableCollection
。如果使用此功能,则不需要List<string>
。
因此,您可以像这样定义ObservableCollection
:
private ObservableCollection<string> pathsCollection;
public ObservableCollection<string> PathsCollection
{
get { return pathsCollection ?? (pathsCollection = new ObservableCollection<string>()); }
}
现在,您只需将项目添加到PathsCollection-Property。第一次访问时,它将被初始化。
在xaml中,您必须执行以下操作:
<ItemsControl ItemsSource="{Binding PathsCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在绑定中,您必须为路径提供.
,因为您的ObservableCollection
的类型为string
。
如果您有一个ObservableCollection
类型的属性,则可以提供要在路径上显示的源属性。