【发布时间】:2012-06-28 14:12:07
【问题描述】:
抱歉,我正在忙于同时学习 MVVM、WPF 和 XAML。
我有一个我创建的问题,我完全不知道应该如何在 MVVM 中处理它。
我拥有的是一个父窗口,其中包含一个绘制图形的用户控件。绘制 XAML 的图形曾经是父窗口的一部分,但由于父窗口非常大,我将其移至用户控件以进行组织。
在父窗口 XAML 中我有.....
<Window ....>
<Window.Resources>
<ViewModel:DropGraphViewModel x:Key="myViewModel"/>
</Window.Resources>
<!-- Set the data context to the view model. -->
<Window.DataContext>
<Binding Source="{StaticResource myViewModel}"/>
</Window.DataContext>
.....
</Window>
然后在新的用户控件 XAML 类中,我创建了一个资源,它是一个“生成器”类,它提供将由图的某些部分使用的东西。看起来是这样的……
<UserControl ......
<!-- Graph resources -->
<Grid.Resources>
<!-- The binding here for ItemsSource represents the collection the graph will be bound to -->
<!-- THIS LINE DOESN'T WORK ANYMORE -->
<Graphs:LineChartGenerator x:Key="generator" ItemsSource="{Binding Source={StaticResource myViewModel}, Path=SampleData}" Width="500" Height="200"> -->
</Grid.Resources>
然后当我想做一些事情时,比如绘制图表线,我曾经通过绑定来引用生成器。
<!-- Connect the points -->
<Polyline Points="{Binding Source={StaticResource generator}, Path=Points}" Stroke="Blue" />
现在我使用嵌套用户控件的问题是,当我在资源中创建“生成器”类的实例时,我无法传入 ItemsSource= 的绑定"{Binding Source={StaticResource myViewModel}, Path=SampleData}" 因为我不再有权访问父窗口静态资源中的视图模型 (myViewModel)!所以我不能像以前那样在资源创建期间设置绑定。
什么是正确的 MVVM 方式来处理这种类型的模式?
如何将 ItemsSource 注入到我的新用户控件中,以便在创建 LineChartGenerator 类实例时将其传入?
【问题讨论】:
标签: wpf mvvm binding user-controls itemssource