How bind button inside user control to another ViewModel - wpf

I'm working on project that based on WPF and MVVM.
I have some UserControl (summaryView) which has DataContext to ViewModel(SummaryVM).
I want put a button in summaryView and set the button DataContex to another viewModel(MainWindowViewModel) but it's not working for me.
This is the NameSpace of the ViewModel
xmlns:vm="clr-namespace:ContentSync.ViewModel"
This is my button
<Button HorizontalAlignment="Left" Width="100" Height="30" Margin="0,20" DataContex=... Command="{Binding ModifyUserSettingsCommand}">Modify</Button>
The command ModifyUserSettingsCommand is located at MainWindowViewModel and the but I don't know how to bind it to my button. I think I need to set it`s DataContext but I didn't succeed in figuring out what is the right syntax
Thanks

Add to UserControl reousrces this:
<UserControl.Resources>
<vm:MainWindowViewModel x:Key="btnViewModel" />
</UserControl.Resources>
And with that way you must assign DataContext to Button:
DataContext="{StaticResource btnViewModel}"

Related

WP7 XAML Bind to property in parent

I'm writting an app in WP7 (Silverlight 3). I have a view model that looks like this
public class MainViewModel
{
public List<ActivityTypes> ActivityTypes{get;set;}
public RelayCommand LoadActivity{get;set;}
}
My pages datacontext is set to the view model and I have a listbox with it's item source set to the ActivityTypes collection. In the listbox I'm trying to render a list of buttons who's command is bound to the LoadActivity property on the viewmodel. RelayCommand is part of the MVVM Light toolkit in case you are wondering what it is.
The problem I am having is I can't find a way to bind my button command to the LoadActivity property as my listbox has it's itemsource set to the Activitytypes collection and this property is in the parent. I've read about FindAncester but it doesn't look like this is supported in Silverlight 3.
My XAML looks like this
<UserControl.Resources>
<DataTemplate x:Key="ActivityTypeListTemplate">
<StackPanel>
<Button Command="{Binding LoadActivity}"> <!--binding not found as we're in the collection-->
<TextBlock Text="{Binding Name}" FontSize="50"/>
</Button>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
<ListBox Margin="0" ItemsSource="{Binding ActivityTypes}" ItemTemplate="{StaticResource ActivityTypeListTemplate}"/>
</Grid>
What's the best way to code something like this?
There is no "direct" way to do this. You can set the Buttons DataContext to your MainViewModel (preferably as a StaticResource link) and the it would work.
Take a look at Bind to parent object in xaml

Change binding source back to view model inside container in XAML

I am using Silverlight 4 and the MVVM pattern.
My view model has two properties:
SomeProperty and
MyCommand
SomeProperty is a complex type and has a lot of subproperties. MyCommand is a property to handle commanding from a Button.
I have a child window (the view) with a Grid as the LayoutRoot which is bound to the SomeProperty property of the view model.
<Grid x:Name="LayoutRoot" DataContext="{Binding SomeProperty, Mode=TwoWay}">
...
</Grid>
However, inside the Grid I want to bind a Button's Command property to the MyCommand property of the view model:
<Button Command={Binding MyCommand} />
But this is not working because MyCommand is a property of the view model, and not a property of the view model's SomeProperty property. (When I click on the Button it does not execute the command.)
Anywho, is there a way using data binding in Silverlight 4 such that I can have a container UI element set its DataContext property explicitly, but then have a different control within the container reference a property that's a sibling (or parent or whatever) of the DataContext of the containing control?
My current workaround is to define the binding in the view's class, but I'd rather have it in the XAML.
Thanks
If you give your root element (ChildWindow, UserControl, whatever) a name, then you can use ElementName to get to the view model.
<UserControl x:Name="MyUserControl">
<Grid x:Name="LayoutRoot" DataContext="{Binding SomeProperty, Mode=TwoWay}">
<Button Command="{Binding MyCommand}" DataContext="{Binding DataContext, ElementName=MyUserControl}" />
</Grid>
</UserControl>
Or, here's another way to do the same thing.
<UserControl x:Name="MyUserControl">
<Grid x:Name="LayoutRoot" DataContext="{Binding SomeProperty, Mode=TwoWay}">
<Button Command="{Binding DataContext.MyCommand, ElementName=MyUserControl}" />
</Grid>
</UserControl>
You try add datacontext to binding? The datacontext have to point to your viewmodel, because the default data context is a parent control or parent data context, in this case your layout root.
See this
and this
I hope this help.
Regards.
I use a version of the BindableProxy described in this post:
http://weblogs.asp.net/dwahlin/archive/2009/08/20/creating-a-silverlight-datacontext-proxy-to-simplify-data-binding-in-nested-controls.aspx
Above your Grid (probably within the UserControl.Resources) you would create:
<UserControl.Resources>
<ns:BindableProxy x:Key="BindableProxy" />
<UserControl.Resources>
Then, in the button binding:
<Button Command="{Binding DataSource.MyCommand, Source={StaticResource BindableProxy}}" />

Command Binding in UserControl used as ListBox.ItemTemplate

I have a Listbox with a UserControl as the DataTemplate. This UserControl has a Button to remove that item from the list.
<ListBox x:Name="FileList" ItemsSource="{Binding Files}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Views:FileItem/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The ItemsSource is defined as:
ObservableCollection<FileViewModel> m_fileViews = new ObservableCollection<FileViewModel>();
Here is the UserControl simplified:
<UserControl x:Class="Views.FileItem">
<Canvas x:Name="LayoutRoot">
<TextBlock x:Name="FileName" Text="{Binding FileName}" />
<Button Content="Remove"/>
</Canvas>
</UserControl>
When the user clicks the Remove button, it should remove this item from the ObservableCollection.
The problem is, the DataContext for each ListBoxItem is a different ViewModel than the ViewModel that holds the ObservableCollection.
I'm not sure how to bind the Remove button to an ICommand in the "parent" ViewModel. Any help would be appreciated. Thanks so much.
I would bind the button to an ICommand in the UserControl's ViewModel, then send a message across to the parent ViewModel using loosely-coupled messaging (available in most Mvvm frameworks, like MvvmFoundation)
Let the parent VM register for the 'remove me' message, and update the ObservableCollection accordingly...
Hope this helps :)

How to wire up a click event for a custom usercontrol button? Should I use CustomControl?

I wanted to create a button that had an image and a textblock as content. So I went about looking for an answer and found a post (Reusable Custom Content for Buttons) which told me to create a usercontrol.
I did this and it works great. I can set the image source and text through dependency properties. However, I am stuck as there is no click event for my control.
I did a little more digging and concluded that I probably need a CustomControl derived from Button. Is this correct? Or would it be better to wire up a click event to my UserControl?
Here's my UserControl:
<UserControl x:Class="Client.Usercontrols.MyButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinHeight="30" MinWidth="40"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Button Width="Auto" HorizontalAlignment="Center">
<Border CornerRadius="5" BorderThickness="1" BorderBrush="Transparent" >
<Grid>
<Image Name="tehImage" Source="{Binding ImageSource}" />
<TextBlock Name="tehText" Text="{Binding Text}"
Style="{DynamicResource ButtonText}" />
</Grid>
</Border>
</Button>
</UserControl>
Implementation
<my:MyButton ImageSource="../Images/MainSyncButton.png" ImageWidth="141" Text="Synchronise" Click="btnSynchronise_Click" />
The easiest option would be to just make your UserControl expose a click event, and pass through your Button's click event.
In MyButton's xaml:
<Button Width="Auto" HorizontalAlignment="Center" Click="onButtonClick">
In MyButton's code:
public event RoutedEventHandler Click;
void onButtonClick(object sender, RoutedEventArgs e)
{
if (this.Click != null)
{
this.Click(this, e);
}
}
You can then leave your "implementation" code as-is.
The answer really depends on what your goals are for the control. You may be able to get away with not creating a user or custom control if you can manipulate the data that you are binding to. If all you want to do is display a dynamic image and text, then you could create an ImageText object that contains two properties. You could then bind the default Button control's Content property to this object and use a DataTemplate to define the layout of the content.
If you cannot control the data type that you are binding to, or if you're really set on the idea of creating a control then I would recommend creating a custom control. Custom controls allow you to utilize the built-in capabilities of a standard button. Generally you would only want to create a User Control if you wanted to hide or encapsulate the default functionality of the visual controls contained within the control.
Good luck.

Data binding custom control with parent

I have a UserControl that contains a listbox.
On the parent window, I have this UserControl and a button.
Ideally I'd like to use the ChangePropertyAction behavior on the parents button, and tie it to the UserControl's listbox count.
The idea being that if there are no entries in the listbox inside the usercontrol, the button on the parent window is hidden. The listbox is bound to an observablecollection.
Do I create a DependencyProperty to do this? I'm not sure how to bind the listbox's count to this property though.
Thanks so much for any insight into the right way to do this.
You can use a ElementName Binding to reach the ListBox state from the Button. You then want to use a BooleanToVisibilityConverter to do the magic.
Like so:
<Window x:Class="NestedTreeTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="200" Width="300">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="boolToVisibilityConverter" />
</Window.Resources>
<StackPanel>
<Button Visibility="{Binding ElementName=myList, Path=HasItems, Converter={StaticResource boolToVisibilityConverter}}">
Text
</Button>
<ListBox x:Name="myList">
<!--<ListBoxItem>Item A</ListBoxItem>-->
</ListBox>
</StackPanel>
</Window>
comment out, or uncomment the ListBoxItems to see it working...
I ended up using the Messenger classes from the MVVM Futures project to let the UserControl's ViewModel signal other ViewModels of the change.
This let's multiple listeners monitor for the same changes, without the need for extra Dependency Properties.

Resources