我正在运行一个简单的MVVM项目,但在第一关卡就失败了。我使用Josh Smith的Relay Command方法绑定命令。
问题是,当按钮位于ResourceDictionary中时,它无法绑定。如果将代码(完全相同)移动到我的MainWindow.xaml文件中,代码将按预期执行。
这是我的MainWindow.xaml文件:
<Window x:Class="ForJon.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:ForJon.Ui.ViewModels"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.Resources>
<ResourceDictionary Source="Resources\ResourceDictionary.xaml" />
</Grid.Resources>
<Grid.DataContext>
<vm:MainWindowViewModel />
</Grid.DataContext>
<HeaderedContentControl
Header="Options"
Style="{StaticResource LeftMenu}"
Grid.Column="0"
/ >
</Grid>
</Window>
同时,需要考虑资源字典
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:view="clr-namespace:ForJon.Ui.Views"
xmlns:viewModel="clr-namespace:ForJon.Ui.ViewModels"
>
<Style x:Key="LeftMenu" TargetType="HeaderedContentControl">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel>
<Button Content="Add" Command="{Binding AddCommand}" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="Width" Value="160"/>
</Style>
</ResourceDictionary>
我只能假设当在ResourceDictionary中绑定时,它找不到ViewModel(虽然我不知道为什么会这样想)。我认为它正在尝试向下多绑定一级... 无论如何,有人能否解释一下为什么它不能从Resource Dictionary中执行。
Style
与一个非常特定的VM和View绑定在一起,这意味着你最好直接在Item本身中定义它。 - Viv