WPF根据observablecollection的变化动态创建用户控件,或者通过使用嵌套的user控件可视化嵌套的ob



我是WPF的新手,我找不到解决问题的方法。

我有一个可观察对象集合在我的ViewModel:

ObservableCollection<Process>

Process类中是另一个ObervableCollection:

ObservableCollection<BurstTime>

我想添加一个新的用户控件(什么可以可视化进程数据的实际状态,它的突发时间)动态到我的StackPanel在我的视图,每次,当一个新的进程被激活,并删除它时,进程结束(当可观察集合的变化)。在它的运行过程中,我想显示它的突发时间集合,什么可以改变的时间…

我试图订阅CollectionChanged事件在我的用户控件的代码背后,并使用另一个用户控件内的用户控件和动态创建所需的TextBlocks当我的事件处理程序运行,但我总是得到一个System.Reflection.TargetInvocationException(内部异常:System.NullReferenceException)当我的外部InitializeComponent()正在运行.

public ResourceUseView()
{
    InitializeComponent();
    ((ObservableCollection<Process>)DataContext).CollectionChanged += ResourceUseView_CollectionChanged;
}

这可能吗?是否有可能在我的外部UserControl的代码背后创建或删除用户控件,同时对ObservableCollection的元素变化作出反应,并在内部ObservableCollection的元素变化时更新外部?是否有其他的方法,而不是实例化一个UserControl在另一个用户控制动态?是否有特殊的控件,什么可以在ObservableCollection中显示ObservableCollection?

(如果可能的话,我希望有不同的用户控制元素我的ObservableCollection有…)

谢谢你的帮助!

构造函数在数据绑定之前运行,所以您可能会看到这个错误,因为在构造函数运行时DataContextnull

要绑定到集合,请使用包含ItemsSource属性的控件。如果您想绑定到一个嵌套集合,修改控件的ItemTemplate以使用另一个具有ItemsSource属性的控件用于嵌套集合。

下面是使用ItemsControl

的示例
<ItemsControl ItemsSource="{Binding Processes}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ItemsControl ItemsSource="{Binding BurstTimes}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

如果你感兴趣的话,我的博客上有一些ItemsControl的例子。

如果你想为每个对象指定一个UserControl,那么将第一个ItemsControlItemTemplate设置为ProcessUserControl,并在ProcessUserControl中将ItemsControl绑定到BurstTimes并使用BurstTimeUserControl为它的ItemTemplate

<ItemsControl ItemsSource="{Binding Processes}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:ProcessUserControl />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

<UserControl x:Class="MyNamespace.ProcessUserControl ...>
    ...
    <ItemsControl ItemsSource="{Binding BurstTimes}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <local:BurstTimeUserControl />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    ...
</UserControl> 

最新更新