我有使用MVVM模型的Windows Phone类库。在我的Generic.xaml
我的CustomElementControl.cs
样式中有CustomElementViewModel.cs
。我还有一个ViewModelLocator.cs
,它将ViewModels与在此上下文中命名为Locator的Controls相关联,但这与此案例无关。现在,如果我像这样添加一个Command按钮:
<Style TargetType="view:CustomElementControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="view:CustomElementControl">
<Page x:Name="pageRoot" DataContext="{Binding Source={StaticResource Locator}, Path=view:CustomElementViewModel, Mode=TwoWay}">
<TextBlock Text="something" Foreground="{Binding Path=ColorTest}" />
<Button Content="MyButton" Command="{Binding MultiSelectCommand}" />
</Page>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
然后像CustomElementViewModel.cs
一样抓住:
private RelayCommand _multiSelectCommand;
public RelayCommand MultiSelectCommand {
get {
if(_multiSelectCommand == null) {
_multiSelectCommand = new RelayCommand(
() => {
this.SelectionMode = (this.SelectionMode == ListViewSelectionMode.Single) ? ListViewSelectionMode.Multiple : ListViewSelectionMode.Single;
});
}
return _multiSelectCommand;
}
}
但是,如果我想将Command事件添加到AppBarButton中,它可以正常工作:
<Style TargetType="viewCustomElementControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="view:CustomElementControl">
<Page x:Name="pageRoot" DataContext="{Binding Source={StaticResource Locator}, Path=view:CustomElementViewModel, Mode=TwoWay}">
<TextBlock Text="something" Foreground="{Binding Path=ColorTest}" />
</Page>
<Page.BottomAppBar>
<CommandBar>
<AppBarButton Icon="AllApps" Label="multiselect" Command="{Binding MultiSelectCommand}" />
</CommandBar>
</Page.BottomAppBar>
</Page>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
永远不会触发RelayCommand。我在这里缺少什么?
更新的
我甚至尝试过像这样设置AppBarButton的DataContext:
<AppBarButton Icon="AllApps" Label="multiselect" Command="{Binding DataContext.MultiSelectCommand, ElementName=pageRoot, Mode=OneWay}" />
和
<AppBarButton Icon="AllApps" Label="multiselect" DataContext="{Binding Source={StaticResource Locator}, Path=CustomElementViewModel, Mode=TwoWay} Command="{Binding MultiSelectCommand}" />
没有效果。
更新2
以下是一个示例:http://1drv.ms/1vRnaYH