【问题标题】:multi Datacontext wpf多数据上下文 wpf
【发布时间】:2019-04-13 17:56:38
【问题描述】:

谁能向我解释如何使用两个不同的数据上下文?

这是我的文件.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,与第一个完全相同,但内容不同。所以每个人的datacontexte都需要不同。

感谢您给我一点时间。

【问题讨论】:

  • 请注意,ListBox 在 ScrollViewer 中看起来很奇怪。 ListBox 已经在其 ControlTemplate 中通过 ScrollViewer 提供滚动。

标签: wpf xaml binding datacontext


【解决方案1】:

您不需要设置不同的 DataContexts。

在 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}" ...>

【讨论】:

  • 感谢您的帮助,这是一个简单的解决方案,非常容易理解。
猜你喜欢
  • 2015-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
相关资源
最近更新 更多