简体   繁体   中英

C# WPF XAML Run XAML Command on UserControl load

I am trying to execute a XAML command, when the Usercontrol gets loaded. The reason for that is that i want to change the theme of my application when the user navigates from Usercontrol A to Usercontrol B. I am using Firstfoor ModernUI.

The Code I want to execute:

 Command="mui:LinkCommands.NavigateLink" CommandParameter="cmd://settheme|/NLauncher;component/designs/ModernUI.BO2ii.xaml"

Usually u execute the Code with a button, but the user navigates with the TabControl included in the ModernUI.

Make sure you have

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

In your <UserControl> tag

Then use this piece of code

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <i:InvokeCommandAction Command="{Binding YourCommand}" CommandParameter = {Binding YourParameter} />
    </i:EventTrigger>
</i:Interaction.Triggers>

You will need to add a reference to System.Windows.Interactivity to your project

Edit : Fixed Event Name Load -> Loaded

Just added full XAML codes with reference to above answered code of Lionel Pire.

<UserControl x:Class="Test.MyClass"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800"
             >
<Grid  Name="mygrid">

</Grid>


<!--Use this below the grid in case any control is passed in command parameter-->
<i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded">
            <i:InvokeCommandAction Command="{Binding myCommand}" 
                       CommandParameter = "{Binding ElementName=mygrid}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</UserControl>

The latest package for XAML Interactions\\Interactivity is now published as Microsoft.Xaml.Behaviors.Wpf

Install it via NuGet package manager:

Install-Package Microsoft.Xaml.Behaviors.Wpf

Sample usage:

xmlns:behaviors="http://schemas.microsoft.com/xaml/behaviors"

<Border>
    <behaviors:Interaction.Triggers>
        <behaviors:EventTrigger EventName="Loaded">
            <behaviors:InvokeCommandAction Command="{Binding MyCommand}"/>
        </behaviors:EventTrigger>
    </behaviors:Interaction.Triggers>
</Border>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM