Wednesday, November 9, 2011

Flash in WPF Application the MVVM way (the easy part)

Now I have to use my WFPFlashLibrary I created in the last post in my main WPF view. I have to add the namespace for the project that contains my Flash control.

xmlns:Flash="clr-namespace:WPFFlashLibrary;assembly=WPFFlashLibrary"

I place my control in the WPF markup and bind Movie and Play.

<Grid>
<Flash:FlashControl Width="400" Height="400" Movie="{Binding Movie,UpdateSourceTrigger=PropertyChanged}" Play="{Binding Play,UpdateSourceTrigger=PropertyChanged}" />
</Grid>

This is the sample code which should be placed in the view. The Init will contain any code that needs to run on the ViewModel creation and will return the instance of the ViewModel. The PlayFlash will be then called right in the constructor of the view for simplicity, but of course it does not have to be there - it can be triggered whenever necessary.

public partial class TestFlashView : System.Windows.Controls.UserControl
{
public TestFlash(IUnityContainer container)
{
InitializeComponent();

DataContext = container.Resolve().Init(container);
(DataContext as TestFlashViewModel).PlayFlash();
}
}

And this is the implementation of the ViewModel. As soon as the PlayFlash() assigns values to the Movie and Play, the control will play the Flash animation (assuming the file is in the specified location!).

public class TestFlashViewModel : ViewModelBase
{
public TestFlashViewModel(IUnityContainer container):base(container)
{

}

virtual public TestFlashViewModel Init(IUnityContainer container)
{
//initialization - login etc.
return this;
}

//*****************************************************************************************

#region properties

string _movie;
public string Movie
{
get { return _movie; }
set { OnPropertyChanged(ref _movie , value,"Movie"); }
}

bool _play;
public bool Play
{
get { return _play; }
set { OnPropertyChanged(ref _play, value, "Play"); }
}

#endregion

public void PlayFlash()
{
Movie = @"c:\flash\flash.swf";
Play = true;
}
}

And that's the end of my small investigation. Unfortunately I found out that the plans have changed, the scope has been reduced and the flash movie is not required any longer. So I won't play with this control for anymore for now and move on to other things. Still was worth the effort.

by . Also posted on my website

No comments: