多数据上下文wpf

时间:2018-11-10 10:23:55

标签: wpf xaml binding datacontext

谁可以向我解释如何使用两个不同的datacontext?

这是我的file.xaml.cs:

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

        DataContext = new string[] { "Female", "Male", "Animal", "Safe", "Soft", "Hard", "Space", "Landscape", "Outside", "Inside",
        "City", "France", "Flower", "Sunset", "Sky", "Fireworks", "Spring", "Winter", "Summer", "Fall", "Christmas", "Halloween",
        "Ghost", "Demon", "Angel", "Watermelon", "Storm", "Waterfall", "Night", "Sun","Moon", "Dog", "Cat", "Food", "Cheese",
        "Kancolle", "IT", "UFO", "Travel", "Sport", "Nightmare"};
   } 

这是我的file.xaml:

<ScrollViewer HorizontalAlignment="Left" Height="170" VerticalAlignment="Top" Width="97" Margin="10,149,0,0">
        <ListBox ItemsSource="{Binding .}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding Path=.}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </ScrollViewer>

一切在这里都可以正常工作,但是我想添加第二个ScrollViewer,就像第一个一样,但是有另一个内容。因此每个数据上下文都需要不同。

感谢您给我一些时间。

1 个答案:

答案 0 :(得分:0)

您无需设置其他DataContext。

在MainWindow类中创建两个集合属性,然后将DataContext设置为窗口实例。

public IEnumerable<string> Collection1 { get; }
public IEnumerable<string> Collection2 { get; }

public MainWindow()
{
    InitializeComponent();

    Collection1 = new string[] { ... }; 
    Collection2 = new string[] { ... }; 
    DataContext = this;
}

将ListBox的ItemSource绑定到集合属性:

<ListBox ItemsSource="{Binding Collection1}" ...>
...
<ListBox ItemsSource="{Binding Collection2}" ...>