多数据上下文 wpf
multi Datacontext wpf
谁能给我解释一下如何使用两个不同的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,与第一个 ScrollViewer 完全一样,但内容不同。因此每个数据上下文都需要不同。
谢谢你给我一点时间。
您不需要设置不同的 DataContext。
在 MainWindow 中创建两个集合属性 class 并将 DataContext 设置为 window 实例。
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}" ...>
谁能给我解释一下如何使用两个不同的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,与第一个 ScrollViewer 完全一样,但内容不同。因此每个数据上下文都需要不同。
谢谢你给我一点时间。
您不需要设置不同的 DataContext。
在 MainWindow 中创建两个集合属性 class 并将 DataContext 设置为 window 实例。
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}" ...>