In order to use Binding
in DataTemplate
, it is necessary to what is the DataContext. Finally, I suspect the DataContext is related to NavigationView.Header but I hadn't made it work. Then I turn to DataTemplate.LoadContent which can establish bindings in code and work definitely and by accident, I make the first way work.
<?xml version="1.0" encoding="utf-8"?>
<Window
x:Class="App2WithAPackagingProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App2WithAPackagingProject"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<NavigationView x:Name="NavigationViewControl">
<NavigationView.HeaderTemplate>
<DataTemplate>
<Grid>
<Button Content="Click Me" Command="{Binding MoveLeftCommand}"></Button>
</Grid>
</DataTemplate>
</NavigationView.HeaderTemplate>
<NavigationView.MenuItems>
<NavigationViewItem Content="A" x:Name="A" />
<NavigationViewItem Content="B" x:Name="B" />
<NavigationViewItem Content="C" x:Name="C" />
</NavigationView.MenuItems>
</NavigationView>
</Window>
namespace App2WithAPackagingProject
{
/// <summary>
/// An empty window that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainWindow : Window
{
// Reference to our view model.
//public UICommand1ViewModel ViewModel { get; set; }
public MainWindow()
{
this.InitializeComponent();
//ViewModel = new UICommand1ViewModel();
NavigationViewControl.DataContext = new UICommand1ViewModel();
// Select one of the DataTemplate objects, based on the
// value of the selected item in the ComboBox.
//DataTemplate template = NavigationViewControl.Resources["oddNumberTemplate"] as DataTemplate;
//UIElement element = template.LoadContent() as UIElement;
UIElement element = new TextBlock();
//Button tb = FindVisualChild<Button>(element);
//tb.Content = "???";
NavigationViewControl.Header = element;
}
...
}
The crucial point is establishing the DataContext of context of NavigationView.Header...