通常,我们不能将多个控件绑定到一个ObservableCollection
在以下情况下可以这样做吗?
一次只能看到一个部分
在这种情况下,同一集合两次出现参考错误
它实际上如何在内部工作?它不应该包含不可见的代码吗?
<Grid Visibility="{Binding B1Visible, Converter={StaticResource BooleanToVisibilityConverter}}">
<ItemsControl ItemsSource="{Binding Elements, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
<!--Another code for B1-->
</Grid>
<Grid Visibility="{Binding B2Visible, Converter={StaticResource BooleanToVisibilityConverter}}">
<ItemsControl ItemsSource="{Binding Elements, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
<!--Another code for B2 -->
</Grid>
答案 0 :(得分:1)
我不知道什么是元素,也不知道您要使用itemscontrol的itempanel的网格到哪里去。
但是。
您可以多次绑定到同一可观察的集合。
在下面的代码中,两个可见性属性为Boolean,转换器将true转换为Visibility.Visible,将false转换为Visibility.Collapsed。
public class MainWindowViewModel : BaseViewModel
{
private ObservableCollection<Person> people = new ObservableCollection<Person>();
public ObservableCollection<Person> People
{
get { return people; }
set { people = value; RaisePropertyChanged();}
}
private bool b1Visible = true;
public bool B1Visible
{
get { return b1Visible; }
set { b1Visible = value; RaisePropertyChanged(); }
}
private bool b2Visible = true;
public bool B2Visible
{
get { return b2Visible; }
set { b2Visible = value; RaisePropertyChanged(); }
}
public MainWindowViewModel()
{
People.Add(new Person { FirstName = "Chesney", LastName = "Brown" });
People.Add(new Person { FirstName = "Gary", LastName = "Windass" });
People.Add(new Person { FirstName = "Liz", LastName = "McDonald" });
People.Add(new Person { FirstName = "Carla", LastName = "Connor" });
}
}
我的标记:
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<StackPanel>
<Grid Visibility="{Binding B1Visible, Converter={StaticResource BooleanToVisibilityConverter}}">
<ItemsControl ItemsSource="{Binding People}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding LastName}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!--Another code for B1-->
</Grid>
<Grid Visibility="{Binding B2Visible, Converter={StaticResource BooleanToVisibilityConverter}}">
<ItemsControl ItemsSource="{Binding People}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding LastName}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</StackPanel>
两个项目控件都是可见的,因此我看到了两次名称列表。