How to bind a button's command inside a data template in winUI3

차준혁 40 Reputation points
2024-03-08T06:38:16.55+00:00

I am working on a project using WinUI3.

You want to create navigation in the Main Window and modify the Header with DataTemplate.
How do I do the <button command="{binding}" within the data template at this time?

 <NavigationView x:Name="NavView" 
                 Loaded="NavView_Loaded"
                 ItemInvoked="NavView_ItemInvoked"
                 BackRequested="NavView_BackRequested"
                 Background="{StaticResource Blue_0D2C72}"
                 PaneTitle="ONE LAB"
                 IsPaneVisible="True"
                 IsPaneToggleButtonVisible="False"
                 IsSettingsVisible="False">
     <NavigationView.Resources>
         <Style TargetType="NavigationView">
             <Setter Property="HeaderTemplate">
                 <Setter.Value>
                     <DataTemplate>
                         <Grid>
                             <Grid.ColumnDefinitions>
                                 <ColumnDefinition Width="*" />
                                 <ColumnDefinition Width="*" />
                             </Grid.ColumnDefinitions>
                             <TextBlock Grid.Column="0"
                                        Text="{Binding }"
                                        FontWeight="Bold"/>
                             <StackPanel Grid.Column="1"
                                         Orientation="Horizontal" HorizontalAlignment="Right">
                                 <dx:DXButton Command="{Binding }"
                                              CornerRadius="20"
                                              MaxWidth="120"
                                              Margin="5">
                                     <StackPanel Orientation="Horizontal">
                                         <FontIcon Glyph="&#xF5B0;"/>
                                         <TextBlock Text="Run"
                                                    FontSize="17"
                                                    Margin="10,0,0,0"/>
                                     </StackPanel>
                                 </dx:DXButton>
                                 <dx:DXButton Command="{Binding NavHeaderButtonCommand}"
                                              CommandParameter="Config"
                                              CornerRadius="20"
                                              MaxWidth="120"
                                              Margin="5">     
                                     <StackPanel Orientation="Horizontal">
                                         <FontIcon Glyph="&#xE713;"/>
                                         <TextBlock Text="Config"
                                                    FontSize="17"
                                                    Margin="10,0,0,0"/>      
                                     </StackPanel>
                                 </dx:DXButton>
                             </StackPanel>
                         </Grid>
                     </DataTemplate>
                 </Setter.Value>
             </Setter>
         </Style>
     </NavigationView.Resources>
     <NavigationView.MenuItems>
         <NavigationViewItem Tag="ONEAPP.Views.HomePage" Icon="Home" Content="HOME" ToolTipService.ToolTip="대시보드 메인" />
         <NavigationViewItem Tag="ONEAPP.Views.ManualPage" Icon="Paste" Content="MANUAL" ToolTipService.ToolTip="매뉴얼" />
     </NavigationView.MenuItems>

         <NavigationViewItem Tag="ONEAPP.Views.MyDevicePage" Content="My Device" Icon="AllApps" ToolTipService.ToolTip="등록한 장치"/>
         <NavigationViewItem Tag="ONEAPP.Views.UserAddPage" Content="UserAddPage" Icon="SolidStar" FontStretch="UltraExpanded" ToolTipService.ToolTip="사용자 추가" />
         <NavigationViewItem Tag="ONEAPP.Views.InfoPage" Content="INFO" Icon="View" ToolTipService.ToolTip="정보"/>
     </NavigationView.FooterMenuItems>
     
     <ScrollViewer>
         <Frame x:Name="RootFrameContent" IsTabStop="True"
                NavigationFailed="ContentFrame_NavigationFailed"
                Background="White"/>
     </ScrollViewer>
 </NavigationView>

This is my code. How do I configure the <dx:DXButton Command="{Binding MyDataTemplate}" at this time?

Command="{Binding DataContext.Btn_AddNewDataModel_Click, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}"

Based on Google searches, it is speculated that UWP uses the following methods. So what method should WinUI3 use?

[RelayCommand]
public void MyDataTemplate(string order)
{
    try
    {
        switch (order)
        {
            case "Run":
                System.Diagnostics.Debug.WriteLine("Run Click");
                break;
            case "Config":
                System.Diagnostics.Debug.WriteLine("Config Click");
                break;
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine($"NavHeaderButton Error: {ex.Message}");
    }
}
Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
722 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,206 questions
{count} votes

Accepted answer
  1. Xiaopo Yang - MSFT 11,256 Reputation points Microsoft Vendor
    2024-03-11T05:59:09.5766667+00:00

    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...

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful