Wpf UI对象,位于XAML树的samelevel上,作为CommandParameter
我有一个XAML树,如下所示:Wpf UI对象,位于XAML树的samelevel上,作为CommandParameter,wpf,binding,mvvm,relativesource,Wpf,Binding,Mvvm,Relativesource,我有一个XAML树,如下所示: <Window> <Grid> <DockPanel> <DataGrid> <DataGrid.Resources> <CheckBox Command="{Binding Command}" CommandParameter="??" /&
<Window>
<Grid>
<DockPanel>
<DataGrid>
<DataGrid.Resources>
<CheckBox Command="{Binding Command}" CommandParameter="??" />
</DataGrid.Resources>
</DataGrid>
<StackPanel>
<ChartLegend>
</ChartLegend>
<DataChart>
</DataChart>
</stackPanel>
</DockPanel>
</Grid>
</Window>
我想从DataGrid
上的命令将DataChart
对象设置为CommandParameter
上的ViewModel
我的调查结果:
我将DockPanel
对象作为CommandParameter
,然后我必须应用方法FindName(“”
)来获取DataChart
。并做进一步的修改
但是我希望直接使用DataChart
对象,以避免TypeCasting
或向下搜索树。您可以将DataChart作为命名资源保存在DockPanel
资源中,并对命令参数使用静态资源绑定。然后使用ContentControl
托管它
像这样
<DockPanel>
<DockPanel.Resources>
<DataChart x:Key="MyDataChart">
</DataChart>
</DockPanel.Resources>
<DataGrid>
<DataGrid.Resources>
<CheckBox
Command="{Binding Command}"
CommandParameter="{StaticResource MyDataChart}" />
</DataGrid.Resources>
</DataGrid>
<StackPanel>
<ChartLegend>
</ChartLegend>
<ContentControl Content="{StaticResource MyDataChart}"/>
</stackPanel>
</DockPanel>
希望您不会使用相同的MyDataChart
托管到另一个区域(因为这将导致“可视化树父断开连接”错误)
虽然我必须问你这个。。。为什么在DataGrid
资源中有一个单独的复选框
您和我的解决方案也破坏了MVVM,因为我们为视图模型提供了UI控件(图表控件)。这是XamDataChart的一个主要缺点,无法通过绑定更新ItemSource,因为它是只读属性。它只能通过带有UI Control.oh的代码进行更新,还有一件事[:(]…我不确定CheckBox的Command/CommandParameter属性是否有效。不知怎么的,它被弃用了。谢谢你的建议。我知道这一点,我只是遵循这个模式。这段代码仅仅是一个表示。现在我还有一个查询,我想在Window.Resources中创建一个常规复选框,并将其用于多个DataGrid。你能给出建议吗?可以通过相对资源吗?我想是的。不可以…不能在多个父项下设置UI控件…因为我们使用模板。因此,在你的情况下,将复选框包装在DataTemplate
下,然后将DataTemplate
设置为合适的父项(例如ContentControl.ContentTemplate
或ItemsControl.itemstemplate
等)