为什么ItemsControl.ItemTemplate中的元素不继承DataContext?

时间:2018-12-25 18:47:46

标签: c# wpf xaml

我正在探索wpf。为什么 ItemsControl.ItemTemplate 中的元素不继承 DataContext

Command="{Binding Maximize}" 

它不继承Window中定义的 DataContext 。为什么?

MainWindow.xaml

<Window ... omitted for brevity
    DataContext="{Binding ViewModel, RelativeSource={RelativeSource Self}}"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <ItemsControl ItemsSource="{Binding cards}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding}"
                        Command="{Binding Maximize}"
                        CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

MainWindowViewModel.cs

 public class MainWindowViewModel
{

    public IList<string> cards { get; set; } = new ObservableCollection<string>();

    public MainWindowViewModel()
    {
        cards = Directory.GetFiles("Cards", "*.txt")
                              .Select(Path.GetFileName).ToList();
    }
    private RelayCommand<Window> _maximize = null;
    public RelayCommand<Window> Maximize => _maximize ??
        (_maximize = new RelayCommand<Window>(MaximizeWindow));

    private void MaximizeWindow(Window obj)
    {
        obj.WindowState ^= WindowState.Maximized;
    }
} 

0 个答案:

没有答案