I have a code similar to the one below and a boolean property, in the viewmodel, that I would like to use to control the Loaded event. As an example, if property is false, do not trigger this event. If there was an IsEnabled property in xaml, it would have been easy to bind the boolean property to. In the case of an event, how to accomplish this task?
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<cmd:EventToCommand Command="{Binding Mode=OneWay, Path=LoadedCommand}"
PassEventArgsToCommand="True" />
</i:EventTrigger>
You can use CanExecute and RaiseCanExecuteChanged methods
of your DelegateCommand in your view model to check the value
and effectively disable the DelegateCommand when needed.
You can also handle the event in the code behind of the view. Your
view model is already the data context of the view so accessing it
from code behind for this purpose is fine and therefore you can
check the boolean property from your view model and cancel the event
as needed.
Related
How do I bind the sorting command of my datagrid to view model?
Below is my XAML Code
<DataGrid ItemsSource="{Binding ViewModels}"
CanUserSortColumns="True"
Sorting="{Binding ViewModel_SortingCommand}">
</DataGrid>
Below is the ViewModel implemented that cause the error in binding
ViewModel_SortingCommand = new DelegateCommand<DataGridSortingEventArgs>(ViewModel_Sorting;
public void ViewModel_Sorting(DataGridSortingEventArgs args)
{
// Error on binding
}
Since Sorting is an event, you cannot bind it directly, but you can use an EventTrigger.
<DataGrid ItemsSource="{Binding ViewModels}"
CanUserSortColumns="True">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Sorting">
<i:InvokeCommandAction Command="{Binding ViewModel_SortingCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</DataGrid>
If you use the legacy blend behaviors shipped with Blend, use this namespace:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
If you use the new Microsoft.Xaml.Behaviors.Wpf Nuget package, use this namespace:
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
If you need to process the event args in your command, set PassEventArgsToCommand to True:
<b:InvokeCommandAction Command="{Binding FavContextMenuEditCmd}" PassEventArgsToCommand="True"/>
Also note, that there is an EventArgsParameterPath property to specify a property in the event args that should be passed to the command and an EventArgsConverter property to use a converter. These are useful to avoid passing UI related types like event args to your view model.
Passing a DataGridSortingEventArgs to a view model breaks the MVVM pattern.
You should either perform the sorting in the view/control or, if you are really interested in the sort order in the context of the view model, sort the actual source collection that the view binds to. In general, the view model isn't interested in or aware of how the user sorts, groups or filter the data in the view.
Either way, the view model should not depend on a DataGridSortingEventArgs or anything else that is related to the DataGrid control in the view.
I would like to add trigger on mouse left click on my control. On trigger, if particular property of view model is set, then set some control property. However if viewmodel property is not set, invoke some command action. Is it achievable in WPF?
Currently I only have
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseRightButtonDown">
<interactivity:InvokeCommandAction AutoEnable="False"
Command="{Binding SomeCommand}"
CommandParameter="{x:Static SomeParameter" />
</i:EventTrigger>
</i:Interaction.Triggers>
I am not sure how to check a condition and based on result either invoke command or set control property.
Please suggest.
I am trying to handle a RoutedEvent from a UserControl I built by hooking it up to a command using Interaction.Triggers. The following works--it calls the AddingNewThingCommand:
<WrapPanel>
<local:MyCustomUserControl Header="MyHeader1"
ItemsSource="{Binding List1}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="AddingNewThing">
<prism:InvokeCommandAction Command="{Binding DataContext.AddingNewThingCommand, ElementName=rootViewElement}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</local:MyCustomUserControl >
<local:MyCustomUserControl Header="MyHeader2"
ItemsSource="{Binding List2}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="AddingNewThing">
<prism:InvokeCommandAction Command="{Binding DataContext.AddingNewThingCommand, ElementName=rootViewElement}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</local:MyCustomUserControl >
</WrapPanel>
Now I actually have a lot of these user control instances in this wrap panel, so I would prefer to move the interaction triggers to the parent element -- the WrapPanel. The following does not work:
<WrapPanel>
<i:Interaction.Triggers>
<!-- Also tried local:MyCustomUserControl.AddingNewThing -->
<i:EventTrigger EventName="MyCustomUserControl.AddingNewThing">
<prism:InvokeCommandAction Command="{Binding DataContext.AddingNewThingCommand, ElementName=rootViewElement}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<local:MyCustomUserControl Header="MyHeader1"
ItemsSource="{Binding List1}"/>
<local:MyCustomUserControl Header="MyHeader2"
ItemsSource="{Binding List2}"/>
</WrapPanel>
Does EventTrigger work with bubbling events?
My RoutedEvent:
public static readonly RoutedEvent AddingNewThingEvent = EventManager.RegisterRoutedEvent(
"AddingNewThing", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyCustomUserControl));
public event RoutedEventHandler AddingNewThing
{
add { AddHandler(AddingNewThingEvent, value); }
remove { RemoveHandler(AddingNewThingEvent, value); }
}
Normally, the routed event system permits handlers for any routed event to be attached to any UIElement or ContentElement. That's how the routed events work.
However, the System.Windows.Interactivity.EventTrigger is not a part of the visual tree and therefore cannot participate in this routed event dispatching. The EventTrigger subscribes directly to the CLR event with given EventName (using Reflection: Type.GetEvent).
The event source object will be determined using the following order:
If SourceObject property of the EventTrigger is set, try to get that object. If it's not null, use it.
If SourceName of the EventTrigger is set, get the object using a named objects resolver.
Otherwise, use the associated object the EventTrigger is directly attached to.
The EventName has to be a simple event name. Fully qualified event names (i.e. Type.EventName) are not supported. This is in contrast with System.Windows.EventTrigger, where you can specify the fully qualified routed event name in the RoutedEvent property.
So in short, you cannot simplify your WrapPanel in that way.
Maybe you could use an ItemsControl with a WrapPanel as ItemsPanel and define a DataTemplate containing your MyCustomUserControl with the EventTriggers.
I'm new to WPF but I manage to advance slowly towards writing my first serious project. I'm not sure I use the correct terms so please bear with me.
I implemented a set of ItemsControl (User Controls). The item source is a collection of items. Each item holds much data including it's own ID. I would like the User Control to change a property when the mouse hovers over another control outside this set of ItemsControl.
To complicate things the other control is also an element of another set of ItemsControl.
I already managed to store the ID of the hovered-over control in a top-level property (In the top DataContext) but I can't find a way to bind to it from within the element buried inside the DataTemplate.
Here's a screenshot:
In this example the user hovers over channel 14 - as a result, bottom axes X and Z should highlight (I chose them arbitrarily - according to data stored in the database).
I'd be grateful for any idea. Examples will be most welcome!
Assuming that:
1) You are using the MVVM design pattern.
2) That there is an underlying ViewModel for each of the items in your ItemsControl.
Then what you need to do is handle the MouseEnter and MouseLeave events in your view and have them trigger Commands in your view model. Then have those ViewModels update properties in your other ViewModels to have them highlight the appropriate items in the other ItemsControl.
<UserControl x:Class="ClassName"
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="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4">
<i:Interaction.Triggers>
<!-- this will call the associated commands on your viewmodel when the mouse enters/leaves the corresponding view in your itemscontrol, from there you can create the viewmodel functionality you'd like-->
<i:EventTrigger EventName="MouseEnter">
<i:InvokeCommandAction Command="{Binding MouseEnterCommand}"/>
</i:EventTrigger>
<i:EventTrigger EventName="MouseLeave">
<i:InvokeCommandAction Command="{Binding MouseLeaveCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid Height="10" Width="10">
<!--the content of your usercontrol-->
</Grid>
</UserControl>
Once you get the correct commands notifying your viewmodel that the mouse is hovering over it (or left it). You can manage the state of your viewmodels to create the affects you are looking for.
I really like the Blend SDK for stuff like this.
Since you mentioned you have the hovered-over ID setting in a property, you could start with a PropertyChangedTrigger at the root level. Next, you will probably want to invoke a command (rather than just a method), since your action includes a parameter (the ID). Use InvokeCommandAction for this. You can trigger a command either on the view or the view-model. If you want to trigger it on the view, then you'll probably want to use ElementName as the binding.
Here's an example.
<UserControl>
<i:Interaction.Triggers>
<!-- When "SelectedID" changes, invoke the "SelectedIDChangedCommand" on the
element "AxesAndButtons". Pass the value of "SelectedID" as the
command parameter -->
<ei:PropertyChangedTrigger Binding="{Binding SelectedID}">
<i:InvokeCommandAction CommandParameter="{Binding SelectedID}"
Command="{Binding ElementName=AxesAndButtons,Path=SelectedIDChangedCommand}" />
</ei:PropertyChangedTrigger>
<i:Interaction.Triggers>
<my:AxesAndButtonsControl x:Name="AxesAndButtons">
</my:AxesAndButtonsControl>
</UserControl>
I have assumed that ID property that gets changed is called "SelectedID" (and is a property of the root data context). Also, that your target user control has a defined ICommand "SelectedIDChangedCommand" dependency property that performs the update. That is, something like this:
public class AxesAndButtonsControl : UserControl
{
public static readonly DependencyProperty SelectedIDChangedCommand = DependencyProperty.Register("SelectedIDChangedCommand",
typeof(ICommand),
typeof(AxesAndButtonsControl),
new PropertyMetadata(null));
public AxesAndButtonsControl()
{
SelectedIDChangedCommand = new DelegateCommand(id => {
// highlight "X" and "Z" or whatever
});
}
}
Edit I just noticed that maybe you haven't bound the MouseOver event to update the SelectedID property yet. If that's the case, then you should be able to use an EventTrigger along with a ChangePropertyAction (in a FindAncestor or ElementName binding) to update it. Something like this:
<DataTemplate>
<Grid>
<i:Interaction.Triggers>
<!-- When "MouseEnter" gets triggered, set the property "SelectedID" on the
data context of the closest "UserControl" parent to the value of "ItemID"
in the current data context -->
<i:EventTrigger EventName="MouseEnter">
<ei:ChangePropertyAction Value="{Binding ItemID}"
TargetObject="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DataContext}"
PropertyName="SelectedID" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Grid>
</DataTemplate>
I am using MvvmLight toolkit for my event interactions, i have tried many solutions available but none worked. The combo box inside my data grid's Selection Changed event is not firing
Here is my xaml:
i used both InvokeCommandAction and EventToCommand:
EventToCommand Command="{Binding rlcCbSelectionChanged, Mode=OneWay}"
PassEventArgsToCommand="True"
InvokeCommandAction Command="{Binding rlcCbSelectionChanged, Mode=OneWay}"
Please tell me what am i missing??
Selection Changed event successfully fires on data grid with same procedure given above.
Well answer is quite simple i was missing an attribute that is optional that is why i leave this one previously but that causes selection change event not to fire. So i add my view model key as a static resource and it worked :)
So my working xaml look like :
<i:EventTrigger EventName="SelectionChanged">
<i1:InvokeCommandAction Command="{Binding Path=rlcCbSelectionChanged, Source={StaticResource dvm}}"/>
</i:EventTrigger>