Bind ICommand to parent ViewModel - c#

I have two user controls LeftPanel and DeviceList. DeviceList is inside the LeftPanel. I want the context menu in device list to be able to call a command on the parent view model, which is set on a grid that hosts DeviceList. I have tried the following but it does not work.
Here is the ContextMenu within DeviceList
<MenuItem Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type local:LeftPanel}},
Path=DeviceListViewModel.RemoveDevice}">
Here is the LeftPanel usercontrol
<UserControl x:Class="Tool.LeftPanel" .... >
<Grid DataContext="{Binding DeviceListViewModel}" Grid.Column="1">
<local:DeviceList Grid.Row="1" Margin="0,0,0,10"/>

I had a similar problem, but the ContextMenu does not see the DataContext of the ViewModel or the Parent.
A possible solution is here Access ViewModel / DataConext inside ContextMenu .

the contextmenu is not part of the visualtree, so i think your binding is simply wrong because the datacontext is not what you think of.
use Snoop to check your DataContext and bindings at runtime
i assume that you have to work with PlacementTarget in your bindings

Related

Binding a ContextMenu item's "IsEnabled" to a Button

Is it possible to bind the IsEnabled property of a button to a context menu item that is represented by a NotifyIcon?
When I push the menu item, it starts a method that disables my btnSave. In that case, I would like to "turn off" the MenuItem too. I attempted it this way, but it's not working:
<Window.Resources>
<ContextMenu x:Key="NotifierContextMenu" Placement="MousePoint">
<MenuItem Header="Start" Click="start_timer" IsEnabled="{Binding ElementName=btnSave, Path=IsEnabled}"/>
</ContextMenu>
</Window.Resources>
I believe your problem stems from a ContextMenu not existing within the visual tree, so ElementName bindings will be unsuccessful, unless you take some additional steps to correct the Name Scope, or resolve the DataContext to the visual tree.
Most of the techniques are covered fairly comprehensively in this answer: ElementName Binding from MenuItem in ContextMenu.
I've had success in the past with binding to a named element by reference, in your case, that would look something like this:
<MenuItem Header="Start"
IsEnabled="{Binding IsEnabled, Source={x:Reference btnSave}}"
Click="btnSave_Click"/>

Unset/Change Binding in WPF

How can I unset the binding applied to an object so that I can apply another binding to it from a different location?
Suppose I have two data templates binded to the same object reference.
Data Template #1 is the default template to be loaded. I try to bind a button command to a Function1 from my DataContext class:
<Button Content="Button 1" CommandParameter="{Binding }" Command="{Binding DataContext.Function1, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
This actually works and the function gets binded. However, when I try to load Data Template # 2 to the same object (while trying to bind another button command to a different function (Function2) from my DataContext class):
<Button Content="Button 2" CommandParameter="{Binding }" Command="{Binding DataContext.Function2, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
It doesn't work and the first binding is still the one executed. Is there a workaround to this?
EDIT (for better problem context):
I defined my templates in my Window.Resources:
<Window.Resources>
<DataTemplate DataType="{x:Type local:ViewModel1}">
<local:View1 />
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModel2}">
<local:View2 />
</DataTemplate>
</Window.Resources>
The View1.xaml and the View2.xaml contain the button definitions that I described above (I want them to command the control of my process flow).
ViewModel1 and ViewModel2 are my ViewModels that implement the interface IPageViewModel which is the type of my variable CurrentPageViewModel.
In my XAML, I binded ContentControl to the variable CurrentPageViewModel:
<ContentControl Content="{Binding CurrentPageViewModel}" HorizontalAlignment="Center"/>
In my .CS, I have a list defined as List<IPageViewModel> PageViewModels, which I use to contain the instances of my two View Models:
PageViewModels.Add(new ViewModel1());
PageViewModels.Add(new ViewModel2());
// Set starting page
CurrentPageViewModel = PageViewModels[0];
When I try to change my CurrentPageViewModel to the other view model, this is when I want the new binding to work. Unfortunately, it doesn't. Am I doing things the right way?
If for some reason you are unable to use just two different DataTemplates, usually because the datatemplates are very large or complex, i suggest using ContentControl and DataTemplateSelector.
In your DataTemplates place another ContentControl, create 2 DataTemplates just containing your button, one with Function1 one with Function2. Create a DataTemplateSelector and set it on the initial ContentControl. The DataTemplateSelector now just need to select the proper template depending on a decision, for example the type of the item or a property on the item etc.
If you still want to unset binding you can do it from code like:
BindingOperations.ClearBinding(txtName, TextBox.TextProperty)
But TemplateSelector approach will be more efficient.

Bind button in DataTemplate to command in the form's ViewModel

My problem is similar to the one described in this question:
WPF MVVM Button Control Binding in DataTemplate
Here is my XAML:
<Window x:Class="MissileSharp.Launcher.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MissileSharp Launcher" Height="350" Width="525">
<Grid>
<!-- when I put the button here (outside the list), the binding works -->
<!--<Button Content="test" Command="{Binding Path=FireCommand}" />-->
<ListBox ItemsSource="{Binding CommandSets}">
<ListBox.ItemTemplate>
<DataTemplate>
<!-- I need the button here (inside the list), and here the binding does NOT work -->
<Button Content="{Binding}" Command="{Binding Path=FireCommand}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
It's just a ListBox, bound to an ObservableCollection<string> named CommandSets (which is in the ViewModel).
This binding works (it displays a button for each item in the collection).
Now I want to bind the button to a command (FireCommand), which is also in the ViewModel.
Here's the relevant part of the ViewModel:
public class MainWindowViewModel : INotifyPropertyChanged
{
public ICommand FireCommand { get; set; }
public ObservableCollection<string> CommandSets { get; set; }
public MainWindowViewModel()
{
this.FireCommand = new RelayCommand(new Action<object>(this.FireMissile));
}
private void FireMissile(Object obj)
{
System.Windows.MessageBox.Show("fire");
}
}
The binding of this button does NOT work.
From what I've understood from the question I linked above, the binding doesn't work because:
(correct me if I'm wrong)
The button is inside the ListBox, so it only "knows" the binding of the ListBox (the ObservableCollection, in this case), but not the binding of the main window
I'm trying to bind to a command in the main ViewModel of the main window (which the button doesn't "know")
The command itself is definitely correct, because when I put the button outside the ListBox (see the XAML above for an example), the binding works and the command is executed.
Apparently, I "just" need to tell the button to bind to the main ViewModel of the form.
But I'm not able to figure out the right XAML syntax.
I tried several approaches that I found after some googling, but none of them worked for me:
<Button Content="{Binding}" Command="{Binding RelativeSource={RelativeSource Window}, Path=DataContext.FireCommand}" />
<Button Content="{Binding}" Command="{Binding Path=FireCommand, Source={StaticResource MainWindow}}" />
<Button Content="{Binding}" Command="{Binding Path=FireCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
Could someone please:
give me the proper XAML to bind the button inside the ListBox to a command in the form's MainViewModel?
point me to a link where this advanced binding stuff is explained in a way that a WPF/MVVM beginner can understand?
I'm feeling like I'm just copying and pasting arcane XAML incantations, and so far I don't have any clue (and can't find any good documentation) how I would figure out by myself in which cases I'd need RelativeSource or StaticResource or whatever instead of a "normal" binding.
It's:
{Binding DataContext.FireCommand,
RelativeSource={RelativeSource AncestorType=ListBox}}
No need to walk up to the root unless you actually change the DataContext along the way, but as the ListBox seems to bind to a property on the main VM this should be enough.
The only thing i recommend reading is the Data Binding Overview, and the Binding class documentation (including its properties).
Also here is a short explanation on how bindings are constructed: A binding consists of a source and a Path relative to that source, by default the source is the current DataContext. Sources that can be set explicitly are: Source, ElementName & RelativeSource. Setting any of those will override the DataContext as source.
So if you use a source like RelativeSource and want to access something in the DataContext on that level the DataContext needs to appear in the Path.
This may be considered unrelated by most, but this search is only 1 of 3 results that you'll find searching for data binding commands to controls inside a data template--as it relates to Xamarin Forms. So, maybe it'll help someone now-a-days.
Like me you may wonder how to bind commands inside a BindableLayout. Credit jesulink2514 for answering this at Xamarin Forums, where it's probably overlooked by many because of all the comments. Here's his solution, but I'm including the link below:
<ContenPage x:Name="MainPage">
<ListView Grid.Row="1"
ItemsSource="{Binding Customers}"
VerticalOptions="Fill"
x:Name="ListviewCustomer">
<ListView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Property}"/>
<Button Command="{Binding BindingContext.ItemCommand, Source={x:Reference MainPage}}"
CommandParameter="{Binding .}">Click me</Button>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
https://forums.xamarin.com/discussion/comment/217355/#Comment_217355

problem with wpf command not executing when button clicked

I have the following XAML in a WPF application. I would like to bind the button to an ICommand in a view model. For some reason, I am not able to see the command from my view.
this is in a user control.
<Grid>
<Grid.DataContext>
<Binding
x:Name="SettingsData"
Path="Data" />
</Grid.DataContext>
.
.
.
<DockPanel Grid.Column="1">
<Button x:Name="SaveButton"
DockPanel.Dock="Top"
Height="25"
HorizontalAlignment="Left"
Margin="70 0 0 0"
Command="{Binding Path=SaveData}"
>Save Changes</Button>
</DockPanel>
</Grid>
Here is my ICommand object -
public ICommand SaveData
{
get
{
if (_saveData == null)
{
_saveData = new RelayCommand(
param => this.saveData(),
param => true
);
}
return _saveData ;
}
}
Does anyone have any idea why I cannot bind to this command?
Thanks for any thoughts....
Looks like you are setting the DataContext of the Grid to the Data property of your ViewModel (or object). If the object that the Data property exposes doesn't provide the SaveData command, you'll have the problem you're describing. Remember the DataContext is inherited from the parent.
If you require that the DataContext is set in that manner, and still require the button to reference the parent DataContext, one option would be to use a RelativeSource to point to an element that has the ViewModel as the DataContext.
In WPF you also have the option of making those commands static and using the {x:Static} markup extension to reach it.
Hope that helps.
EDIT: Here's an example if your <Grid> is contained in a <UserControl>.
<Button Command="{Binding Path=DataContext.SaveData,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type UserControl}}}" ... />
Also, I don't know what your full XAML looks like, but I suspect that this can be simplified greatly by removing the DataContext on the Grid and Binding Data on the ItemsControl (or whatever you're using to show the list of objects).
Looking at below error, looks like your DataContext on DockPanel is bound to some sort of List:
I see this in the output window - BindingExpression path error:
'SaveData' property not found on 'object' ''List`1'
Please override Source attribute in Binding if the DataContext is not at the top level

Command databinding issues with UserControl - separating DataContext?

In a question I had posted before regarding databinding and UserControls, I was having problems getting simple properties set so that I could change colors, size, etc. Kent gave me some great pointers and that worked great. I then authored a new UserControl, and using his advice, had that working great as well.
Now I'm at the next step -- databinding commands. My current structure looks like this:
Window --contains--> UserControlB --contains--> UserControlA
Now databinding properties in UserControlA work great, and my UserControlB exposes these same properties so that the Window can change UserControlA indirectly. The problem is that UserControlB's DataContext is set something like this:
<UserControl x:Name="root">
<Grid DataContext="{Binding ElementName=root}">
...
<Button Command="{Binding MyCommand}" />
...
</Grid>
</UserControl>
But I want MyCommand to be bound to my ViewModel. I thought it wass possible to set the DataContexts separately, but how do I get the Buttons to point to my ViewModel in XAML?
I found a related post, but didn't sound like what I want to do. I want to create the ViewModel in code, not in XAML.
Your binding should look something like this:
<Button Command="{Binding Path=DataContext.MyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TypeOfYourControlWithViewModelDataContext}}"/>

Categories