我有一个基于Grid控件的自定义用户控件。我有一个ViewModel将它作为属性公开。我希望视图上的XAML绑定到此。我相信这一定很容易,但我对WPF很新。这是如何实现的?
非常感谢提前
(编辑添加更多信息)
视图没有绑定到ViewModel的示例。请注意,我有一个自定义网格,其中包含许多自定义堆栈面板,其中包含许多自定义标题内容控件。这些是在ViewModel加载期间确定的。
<MyCustomGrid:CustomGrid>
<MyCustomGrid:CustomStackPanel>
<MyCustomGrid:CustomHeaderedContentControl/>
</MyCustomGrid:CustomStackPanel>
<MyCustomGrid:CustomStackPanel>
<MyCustomGrid:CustomHeaderedContentControl/>
</MyCustomGrid:CustomStackPanel>
</MyCustomGrid:CustomGrid>
ViewModel只包含一个包含List等的List。请注意,CustomGrid是一个列表,因为可以有多个,但只有一个具有特定属性的列表将被绑定。
答案 0 :(得分:0)
我仍然不确定你想要达到什么目标,但无论如何我都会去,也许我们可以从那里迭代到解决方案。
从上面的XAML判断,您有几个自定义控件。你提到顶级是基于Grid的。 Grid是控件中的,还是ItemsControl的ItemPanelTemplate?
我有点觉得你想要数据绑定你的viewmodel的内容,为此你需要在ItemsControl上建立自定义控件。如果我错了,请纠正我。
像这样的东西(如提到的,这是假设MyCustomGrid为ItemsControl:
<UserControl Name="MyCustomGrid">
<ItemsControl ItemsSource="{Binding Path=MyStackPanelsCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="{x:Type MyCustomGrid:MyCustomStackPanel}">
<Setter Property="Grid.Row" Value="{Binding Path=GridRow}" />
<Setter Property="Grid.Column" Value="{Binding Path=GridColumn}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type MyCustomGrid:MyCustomStackPanelViewModel}">
<ContentPresenter Content="{Binding Path=MySerializedObjectTurnedInToControl}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</UserControl>
如果不是这种情况,就像将您的CustomStackPanel等直接绑定到viewmodel中的一个命名属性一样,它可能看起来像:
<MyCustomGrid:CustomGrid DataContext="{Binding Path=ViewModel}">
<MyCustomGrid:CustomStackPanel DataContext="{Binding Path=MyFirstStackPanelViewModel}">
...
对不起,如果我仍然误解,我很可能会遗漏一些明显的东西。
答案 1 :(得分:0)
基本步骤
将用户控件的DataContext(或包含用户控件的控件/窗口)设置为某个模型类型实例,其数据属性为ObservableCollection<SomeDataType>
。
将ListView
的{{1}}绑定到ItemSource
属性。
将Data
的{{1}}属性绑定到GridViewColumn
的属性。
因此你会有这样的事情:
DisplayMemberBinding
您可以绑定到其他类型,并控制格式化等,但这是一个简单的案例。