Trigger animation inside listbox datatemplate from viewmodel using MVVMLight - silverlight

To learn WP7 i'm making a simple soundboard application.
This is my code.
Please ask if i accidentally left something out in my tries to keep things simple.
MainViewModel contains this collection
public ObservableCollection<SoundViewModel> Sounds { get; private set; }
The soundViewModel contains these properties, they are both notifying any property changes
public string FileName
public string Name
Xaml / View contains a listbox bound to the Sounds collection on the viewmodel
<ListBox x:Name="FirstListBox" Margin="0,0,-12,0" ItemsSource="{Binding Sounds}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Content="Play" CommandParameter="{Binding FileName}" Command="{Binding DataContext.PlaySound, ElementName=FirstListBox}" />
<es:Arc x:Name="arc" ..bla bla attributes. />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
When i click the button, the parameter / filename is used to located the file and invoke the following method.
This method is enclosed in a RelayCommand and bound to the button in the datatemplate
private void PlaySound( string filename )
{
Stream stream = TitleContainer.OpenStream(filename + ".wav");
SoundEffect effect = SoundEffect.FromStream(stream);
PlayAnimation message = new PlayAnimation(effect.Duration);
Messenger.Default.Send<PlayAnimation>(message);
FrameworkDispatcher.Update();
effect.Play();
}
This works great.
Now i want a small animation playing while the sound is playing.
I'm thinking that i will just pass the length of the soundclip to the animation and then start it.
The messenger class sends a message (in the PlaySound method, above), and this code wires it up to a method
------ View / Xaml Constructor ------
Messenger.Default.Register<PlayAnimation>(this, ( action ) => PlayAnimation(action));
------ method PlayAnimation below ------
private void PlayAnimation(PlayAnimation parameter)
{
//Magic code starting the animation in the datatemplate of the listbox..
}
But i'm not exactly sure how i can start the animation.
The storyboard is a resource to the listbox, and the targetElement is the Arc element.
So the animation is simply the arc element's startAngle, and is just there to illustrate that a sound i currently playing, and how long the sound duration is.
Somehow i need to get a hold of the storyboard, but since the targetElement is inside a data-template, how will i know how to play the correct animation. That is if i'm even able to get reference to the storyboard?
Thanks in advance!
Please ask if there is anything

First off define your animation in your data template.
Next instead of binding the CommandParameter to "FileName" bind it to the object in your data template where the animation is defined. Normally your data template will contain a root layout panel where the animation is defined as a resource. Make sure that has an x:Name and bind your CommandParameter to that. So if your root layout container were called "grid" bind the CommandParameter to it like this.
CommandParameter="{Binding ElementName=grid, Mode=OneWay}"
Now in the handler for your relay command change the parameter to reflect that you are now passing in a FrameworkElement rather than your file name string. Also change your code to extract the Storyboard and use the DataContext to get back to your viewmodel to get the filename of the sound.
private void PlaySound( FrameworkElement obj )
{
var animation = obj.Resources["MyAnimation"] as Storyboard;
animation.Begin();
var selected = obj.DataContext as SoundViewModel;
var filename = selected.FileName;
Stream stream = TitleContainer.OpenStream(filename + ".wav");
SoundEffect effect = SoundEffect.FromStream(stream);
PlayAnimation message = new PlayAnimation(effect.Duration);
Messenger.Default.Send<PlayAnimation>(message);
FrameworkDispatcher.Update();
effect.Play();
}

Related

WPF MVVM Bind User Control to Main Window View Model

I asked a similar question a while back here WPF MVVM User Control. I got some answers, but they were way off, so I guess I wasn't clear in what I want to do....
I am working on a WPF application using MVVM. The app is built using a component based approach, so I have some user controls that I've defined that will be used throughout the application. As an example, I have an Address control. I want to use it an multiple places throughout the application. Here's an example. See here:
http://sdrv.ms/1aD775H
The part with the green border is the Address control. The control has its own View Model.
When I place it on a window or other control, I need to tell it the PK of the customer to load addresses for. So I created a Customer ID DependencyProperty:
public partial class AddressView : UserControl
{
public AddressView()
{
InitializeComponent();
}
public static DependencyProperty CustomerIdProperty = DependencyProperty.Register("CustomerId", typeof(int), typeof(AddressView),
new UIPropertyMetadata(0, AddressView.CustomerIdPropertyChangedCallback, AddressView.CustomerIdCoerce, true));
public int CustomerId
{
// THESE NEVER FIRE
get { return (int)GetValue(CustomerIdProperty); }
set { SetValue(CustomerIdProperty, value); }
}
private static void CustomerIdPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
// THIS NEVER FIRES
AddressView instance = (AddressView)d;
instance.CustomerId = (int)args.NewValue;
}
enter code here
private static object CustomerIdCoerce(DependencyObject d, object value)
{
return value; // <=== THIS FIRES ON STARTUP
}
}
Then in the MainWindowView I have:
<vw:AddressView Grid.Row="1"
Grid.Column="0"
x:Name="AddressList"
CustomerId="{Binding ElementName=TheMainWindow, Path=SelectedCustomer.Id, Mode=TwoWay}"/>
Note my comments in the user control's CS. The Coerce fires on startup. The callback never fires, nor do the CustomerId getter or setter.
What I would like to happen seems simple, I just can't make it work....
When a customer is selected the CustomerId should be passed to the Address UserControl. Then in the VM for the Address UserControl should handle getting & saving the data.
So, again, 2 questions:
1) Anyone see what's wrong?
2) How does the UserControl DP send the PK to the ViewModel?
If anyone's interested, my sample project is here: http://sdrv.ms/136bj91
Thanks
Your CustomerId getter and setter will never fire in this situation. They are there simply as helper methods in case you want to access the CustomerIdProperty property from your code behind.
Your CustomerIdPropertyChangedCallback method will not fire because your binding expression is incorrect. You need to bind to the DataContext of MainWindow and not the window itself:
...
CustomerId="{Binding ElementName=TheMainWindow, Path=DataContext.SelectedCustomer.Id}"
...
Also, make sure that you are calling the INotifyPropertyChanged PropertyChanged event when the property bound to the ComboBox is changed.
Try this :
CustomerId="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}, Path=DataContext.YourSelectedItem.TheProperty}"
I am not sure how to manage your seleted item in window, so please change yourSelectedItem.TheProperty accordingly.

How to pass my view model to a user to main view model?

I made a main window that displays various user controls in a content control. In this window, I have the user controls and their accompanying view models in the XAML as DataTemplate Resources. This window has a button that needs to display the user control in the contentcontrol and instantiate the view model for it. How can i pass the resource to my RelayCommand, so that i can tell the command which user control and view model to use? I figured out how to pass a hard-coded string as the command parameter, but now I'm wanting to pass the x:Name so i can reuse this command etc for more than one View-ViewModel.
Main Window's XAML snippets:
<Window.Resources>
<!--User Controls and Accompanying View Models-->
<DataTemplate DataType="{x:Type EmployerSetupVM:EmployerSetupVM}" x:Key="EmployerSetup" x:Name="EmployerSetup">
<EmployerSetupView:EmployerSetupView />
</DataTemplate>
<DataTemplate DataType="{x:Type VendorSetupVM:VendorSetupVM}">
<VendorSetupView:VendorSetupView />
</DataTemplate>
</Window.Resources>
<Button Style="{StaticResource LinkButton}" Command="{Binding ShowCommand}" CommandParameter="{StaticResource EmployerSetup}">
...
In the Main Window's ViewModel, here relevant code so far:
public RelayCommand<DataTemplate> ShowCommand
{
get;
private set;
}
ShowCommand = new RelayCommand<string>((s) => ShowExecuted(s));
private void ShowExecuted(DataTemplate s)
{
var fred = (s.DataType); //how do i get the actual name here, i see it when i hover with intellisense, but i can't access it!
if (!PageViewModels.Contains(EmployerSetupVM))
{
EmployerSetupVM = new EmployerSetupVM();
PageViewModels.Add(EmployerSetupVM);
}
int i = PageViewModels.IndexOf(EmployerSetupVM);
ChangeViewModel(PageViewModels[i]);
}
...
in other words, how do i get the name of the my DataTemplate w/ x:Key="EmployerSetup" in the XAML? If it matters, I'm using MVVMLight too
Try using the Name property of the class Type:
private void ShowExecuted(DataTemplate s) {
var typeName = s.DataType as Type;
if (typeName == null)
return;
var className = typeName.Name; // className will be EmployerSetupVM or VendorSetupVM
...
}
I'd still say passing the DataTemplate to the VM just seems strange. I'd just have two commands and switch the command used in the Button.Style according to the conditions you got.
If you "have" to use a single RelayCommand or the world might end, I'd tend to use a static enum that you can reference from xaml for CommandParameter than pass the whole DataTemplate object.

WPF VB.NET - Reference Controls in MainWindow from a Module

I want to use modules in my first WPF application, as I'm used to using them in WinForm applications I've created before. So I have this button, with a textblock inside.
MainWindow.xaml:
<Button x:Name="Connection_Button" Width="200" Height="30" Margin="5,5,5,5">
<TextBlock FontSize="14" MouseDown="TextBlock_MouseDown">CONNECT</TextBlock>
</Button>
Before in WinForms I could easily reference a button and it's text property by adding MainForm. before the control, but how can I do this in WPF through modules, similar to below? How do I even declare the controls at the top of my module code? And elements inside a control such as TextBlock?
Module_Connection.vb in my old WinForm way:
Private Sub Connect()
If MainForm.Connection_Button.Text = "Connect" Then
' Code
You don't usually do this in WPF.
To base your application logic in the state of UI elements is not really a good idea.
Why? because UI is Not Data and therefore you should base your application logic on the state of data items instead.
I suggest you read this and this
To try to use WPF the same way you use winforms is a straight path to miserable failure and suffering.
You must embrace MVVM and understand DataBinding and how the UI must always be separate from Application Logic and Data.
Edit: Adding a Code Sample (in C#)
ViewModel:
public class MainViewModel
{
public string ButtonContent {get;set;} //TODO: Add Property Change Notification
public MainViewModel()
{
ButtonContent = "SomeButtonContent";
}
}
View:
<Button Width="200" Height="30" Margin="5,5,5,5">
<TextBlock FontSize="14" Text="{Binding ButtonContent}"/>
</Button>
Code Behind:
public class MainWindow: Window
{
public MainWindow()
{
InitializeComponent();
SomeModule.Instance = new MainViewModel();
DataContext = SomeModule.Instance;
}
}
Module (static class in C#):
public static class SomeModule
{
public static MainViewModel Instance {get;set;}
public void DoSomething()
{
if (Instance.ButtonContent == "SomeButtonContent")
//...etc
}
}
This is what I mean by separating the UI from the data. You place your strings in a ViewModel, not in the View, then you evaluate the value of those ViewModel properties to determine what to do.
Still, basing your application logic on the value of a string seems like a weak solution. What do you really need to do? There are much better approaches such as using an Enum for this.
Edit2:
Having a ViewModel to Bind to does not "complicate" things. It actually simplifies them a LOT.
How? because you're now doing this with simple controls, but then you'll want to do the same thing with UI elements inside a ControlTemplate or even worse a DataTemplate and that's when real problems arise.
Therefore, you must get used to "the WPF Way" before you deal with more complex UI scenarios.
Non-optimal approach:
public class MainWindow: Window
{
public string ButtonContent
{
get
{
return this.txtButtonContent.Text;
}
set
{
this.txtButtonContent.Text = value;
}
}
}
<Button Width="200" Height="30" Margin="5,5,5,5">
<TextBlock x:Name="txtButtonContent" FontSize="14" Text="Connect"/>
</Button>
You must understand that the Button class doesn't have a Text property in WPF. In contrast to most ancient framweworks, WPF has a Content Model where literally anything can contain anything with little to no restrictions. Putting a Text property to the Button would be to introduce the limitation for the Button to only contain Text, which is not the case in WPF.
Therefore, what you actually want to do here is to modify the Text property of the TextBlock (which happens to be inside the Button, but could actually be anywhere in the Visual Tree).
That's why I mentioned the fact that you actually NEED a ViewModel to hold your data, because there is no (easy) way to access the UI elements located, for example within a DataTemplate in order to manipulate them. Your UI must always be a reflection of the state of your application's Data, which is stored in Model or ViewModel classes, not the UI.
This should get you in the ballpark:
Module:
Public Sub Connect(RyRef txtBox as TextBox)
If txtBox.Text = "...
note Public vs. Private
Call:
Call .Connect(MyTextBox1)
Call and are optional
I'll answer your question in VB.NET and not provide C# samples of alternative ways of doing it which if you're not used too can be an uphill struggle.
Declare this in your module, access the controls through rootWindow.
Private rootWindow As MainWindow = TryCast(Application.Current.MainWindow, MainWindow)
Another approach is :
Dim mw as MainWindow = Application.Current.Windows.OfType(Of MainWindow).First
assuming you have a MainWindow and only have one MainWindow.

WPF Binding to UserControl Custom DependencyProperty

I have a custom UserControl called SongDescription:
<UserControl x:Class="DPTestAp.SongDescription" ...>
<Grid x:Name="LayoutRoot">
<DockPanel Height="50">
<TextBlock x:Name="title" Text="{Binding name}" Width="100" Height="30"/>
<TextBox x:Name="lyrics"/>
</DockPanel>
</Grid>
</UserControl>
I added DependencyProperty to it:
public partial class SongDescription : UserControl
{
public static readonly DependencyProperty SongProperty = DependencyProperty.Register("Song", typeof(Song), typeof(SongDescription));
public Song Song
{
get
{
return (Song)GetValue(SongProperty);
}
set
{
SetValue(SongProperty, value);
updateLyrics()
}
}
private void updateLyrics()
{
lyrics.Text = Song.lyrics;
}
public SongDescription()
{
InitializeComponent();
}
}
The question is: how to bind something to this SongProperty?
I use SongDescription in my main window like this:
<local:SongDescription x:Name="songDescription" Song="{Binding DataContext}"/>
I cannot make my TextBox lyrics show lyrics. In main window I tried to set DataContext to songDescription, like this:
songDescription.DataContext = new Song() { name="Home", lyrics="Hold on, to me as we go" };
or to window itself like this:
DataContext = new Song() { name="Home", lyrics="Hold on, to me as we go" };
I even tried to make Song a resource and bind it to SongProperty like this:
<Window.Resources>
<local:Song x:Key="res" name="Home" lyrics="Hold on, to me as we go"/>
</Window.Resources>
<Grid>
<local:SongDescription x:Name="songDescription" Song="{StaticResource res}"/>
</Grid>
Nothing helped. TextBlock title binds song name fine. But I can't make updateLyrics() method be called. (In real life this method is more complicated, so I can't use Binding like with name).
Thank you!
Yup, so that's a gotcha with dependency properties. You never ever put validation code inside of the accessor methods (get/set) because dependency properties are stored by WPF in a table that it itself manages. This is why you have to register dependency properties, it essentially creates entries on this table for storing the values associated with each property, and when you use 'GetValue' / 'SetValue' you are updating the entries on this table (which by the way relates to how WPF is able to manage data bindings in general).
The upshot of this though is that WPF can (and will) completely bypass your property accessors because it has direct access to the real data. Why should it use your accessors if it can just go to the data directly. Instead you need to implement a 'PropertyChanged' callback function or some WPF sanctioned method of doing validation, but never ever do it in your accessors.
See:
http://msdn.microsoft.com/en-us/library/ms752914.aspx
In addition to sircodesalot's answer, you are not bound on your lyrics textbox. Also, since the song your bound to is a class, you will need to specify the paths fully for the properties you want to show in the boxes such as "Path=Song.Lyrics".
Another thing to consider is that with dependency properties; your mode will be oneway by default so making the text field editable would be moot really unless you change it.
Third, if you're using MVVM you only need your main window context to be set to the view model and have a matching Song property to bind against.

How to pass the selectedItem of a listbox to the View Model

This is a running question that I have updated to hopefully be a little more clear.
In short what I am trying to accomplish is pass a property from a listbox selected item to the viewmodel so that this property can be used within a new query. In the code below the Listbox inherits databinding from the parent object. The listbox contains data templates (user controls) used to render out detailed results.
The issue I am having is that within the user control I have an expander which when clicked calls a command from the ViewModel. From what I can see the Listbox object is loosing it's data context so in order for the command to be called when the expander is expanded I have to explicitly set the datacontext of the expander. Doing this seems to instantiate a new view model which resets my bound property (SelectedItemsID) to null.
Is there a way to pass the selected item from the view to the viewmodel and prevent the value from being reset to null when a button calls a command from within the templated listbox item?
I realize that both Prism and MVVMLite have workarounds for this but I am not familiar with either framework so I don't know the level of complexity in cutting either of these into my project.
Can this be accomplished outside of Prism or MVVMLite?
original post follows:
Within my project I have a listbox usercontrol which contains a custom data template.
<ListBox x:Name="ResultListBox"
HorizontalAlignment="Stretch"
Background="{x:Null}"
BorderThickness="0"
HorizontalContentAlignment="Stretch"
ItemsSource="{Binding SearchResults[0].Results,
Mode=TwoWay}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
SelectionChanged="ResultListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<dts:TypeTemplateSelector Content="{Binding}" HorizontalContentAlignment="Stretch">
<!-- CFS Template -->
<dts:TypeTemplateSelector.CFSTemplate>
<DataTemplate>
<qr:srchCFS />
</DataTemplate>
</dts:TypeTemplateSelector.CFSTemplate>
<!-- Person Template -->
<dts:TypeTemplateSelector.PersonTemplate>
<DataTemplate>
<qr:srchPerson />
</DataTemplate>
</dts:TypeTemplateSelector.PersonTemplate>
<!-- removed for brevity -->
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
SelectionChanged calls the following method from the code behind
private void ResultListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (((ListBox)sender).SelectedItem != null)
_ViewModel.SelectedItemID = (((ListBox)sender).SelectedItem as QueryResult).ID.ToString();
this.NotifyPropertyChanged(_ViewModel.SelectedItemID);//binds to VM
}
Within the ViewModel I have the following property
public string SelectedItemID
{
get
{
return this._SelectedItemID;
}
set
{
if (this._SelectedItemID == value)
return;
this._SelectedItemID = value;
}
}
the listbox template contains a custom layout with an expander control. The expander control is used to display more details related to the selected item. These details (collection) are created by making a new call to my proxy. To do this with an expander control I used the Expressions InvokeCommandAction
<toolkit:Expander Height="auto"
Margin="0,0,-2,0"
Foreground="#FFFFC21C"
Header="View Details"
IsExpanded="False"
DataContext="{Binding Source={StaticResource SearchViewModelDataSource}}"
Style="{StaticResource DetailExpander}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Expanded">
<i:InvokeCommandAction Command="{Binding GetCfsResultCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
Within the ViewModel the delegate command GetCFSResultCommandExecute which is called is fairly straight forward
private void GetCfsResultCommandExecute(object parameter)
{
long IdResult;
if (long.TryParse(SelectedItemID, out IdResult))
{
this.CallForServiceResults = this._DataModel.GetCFSResults(IdResult);}
The issue I am experiencing is when selecting a listbox Item the selectionchanged event fires and the property SelectedItemID is updated with the correct id from the selected item. When I click on the expander the Command is fired but the property SelectedItemID is set to null. I have traced this with Silverlight-Spy and the events are consistent with what you would expect when the expander is clicked the listbox item loses focus, the expander (toggle) gets focus and there is a LeftMouseDownEvent but I cannot see anything happening that explains why the property is being set to null. I added the same code used in the selection changed event to a LostFocus event on the listboxt item and still received the same result.
I'd appreciate any help with understanding why the public property SelectedItemID is being set to null when the expander button which is part of the listbox control is being set to null. And of course I would REALLY appreciate any help in learning how prevent the property from being set to null and retaining the bound ID.
Update
I have attempted to remove the datacontext reference from the Expander as this was suggested to be the issue. From what I have since this is a data template item it "steps" out of the visual tree and looses reference to the datacontext of the control which is inherited from the parent object. If I attempt to set the datacontext in code for the control all bindings to properties are lost.
My next attempt was to set the datacontext for the expander control within the constructor as
private SearchViewModel _ViewModel;
public srchCFS()
{
InitializeComponent();
this.cfsExpander.DataContext = this._ViewModel;
}
This approach does not seem to work as InvokeCommandAction is never fired. This command only seems to trigger if data context is set on the expander.
thanks in advance
With this line you create a new SearchViewModelDataSource using its default constructor.
DataContext="{Binding Source={StaticResource SearchViewModelDataSource}}"
I guess this is why you find null because this is the default value for reference type.
You can resolve the issue by setting DataContext to the same instance used to the main controll (you can do it by code after all components are initialized).
Hope this help!
Edit
I don't think that binding may be lost after setting datacontext from code. I do it every time I need to share something between two or more model.
In relation to the code you've written :
private SearchViewModel _ViewModel;
public srchCFS()
{
InitializeComponent();
this.cfsExpander.DataContext = this._ViewModel;
}
Instead of using this.cfsExpander you can try to use the FindName method. Maybe this will return you the correct instance.
object item = this.FindName("expander_name");
if ((item!=null)&&(item is Expander))
{
Expander exp = item as Expander;
exp.DataContext = this._ViewModel;
}
Try if its work for you.
Of course, this._ViewModel has to expose a property of type ICommand named GetCfsResultCommand but I think this has been already done.
While this was a hacky approach I found an intermediate solution to get the listbox item value to the view model. I ended up using the selection changed event and passing the value directly to a public property wihtin my view model. Not the best approach but it resolved the issue short term
private void ResultListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (((ListBox)sender).SelectedItem != null)
_ViewModel.SelectedItemID = (((ListBox)sender).SelectedItem as QueryResult).ID.ToString();
MySelectedValue = (((ListBox)sender).SelectedItem as QueryResult).ID.ToString();
this.NotifyPropertyChanged(_ViewModel.SelectedItemID);
}
For this to fire I did have to also setup a property changed handler within the view to push the change to the VM. You can disregard the MySelectedValue line as it is secondary code I have in place for testing.
For those intereted the generic property changed handler
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}

Resources