【发布时间】:2011-06-15 04:05:53
【问题描述】:
我在 WPF 中的命令和数据模板有问题,我不知道这是错误还是正常行为。
我有一个包含列表视图的 CustomControl。此控件用于多个视图(UserControl 的实例)。控件中包含的listview的datatemplate为:
<DataTemplate x:Key="StandardContentDisplayDataTemplate">
<Grid d:DesignWidth="193.333" d:DesignHeight="128.036" Margin="25">
<Button Style="{Binding ItemButtonStyle, RelativeSource={RelativeSource AncestorType={x:Type Control:ContentDisplay}}}"
Margin="0"
VerticalContentAlignment="Stretch"
HorizontalContentAlignment="Center"
Command="{Binding DataContext.ItemTouchCommand, RelativeSource={RelativeSource AncestorType={x:Type Control:ContentDisplay}}}"
CommandParameter="{Binding Id}"
Background="{Binding HexadecimalColor, FallbackValue=#FFAAAA}" BorderThickness="0" HorizontalAlignment="Stretch" Padding="0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="3*"/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name, FallbackValue=Mon Item}" HorizontalAlignment="Center" VerticalAlignment="Center" ToolTipService.ToolTip="{Binding Name}" FontSize="14.667" Margin="0" Grid.Row="0"/>
<Image Margin="1,0,1,1" Grid.Row="1" VerticalAlignment="Stretch" Source="{Binding ImageUrl, FallbackValue=/logo.png, TargetNullValue=/logont.png}" Stretch="Uniform" />
</Grid>
</Button>
</Grid>
</DataTemplate>
我所做的是将命令绑定到 ContentDisplay(这是我的 CustomControl)的数据上下文,也就是说,我的 ViewModel。
链接到这个命令的动作是导航到另一个视图,该视图包含相同的控件,也是其 ViewModel 中的一个命令,以相同的方式绑定(它总共有 3 个级别)。
当我单击顶层视图中的按钮时,它会正确导航到第二层视图,显示其他项目。但是当 ViewModel 被实例化并且命令绑定到列表视图中的项目时,命令被再次调用,一次又一次。 我的理论是 DataTemplate 在绑定命令时会通知其所有父级(所有实例)。但也许我的代码中某处存在错误。
这种行为正常吗?如果是,有没有办法以尊重 MVVM 的方式实现我想要实现的目标?
提前感谢您的回复
【问题讨论】:
-
如果不查看 VM 中的命令代码,就很难说出任何事情。
-
很抱歉,没有错误。这种方式非常有效,实际上我认为执行命令只是从绑定到集合中每个项目的“获取”......请不要怪我:S
-
同意。我知道实例化包含对象时不会调用命令,因此您可以排除这种情况。
标签: .net wpf mvvm command datatemplate