Stephan Ronald
Stephan Ronald

Reputation: 1405

Access instance of UI element in view model in windows phone

In my xaml page i am using an image control

<Image x:Name="MyImage" Grid.Row="1" Stretch="UniformToFill" Source="{Binding SourceImage}"/>

like this. My question is. Is it possible to access this control's properties in my view model. "Like MyImage.Source =". If yes, how i can achieve similar implementation in windows phone.

Upvotes: 1

Views: 458

Answers (1)

vidstige
vidstige

Reputation: 13085

Yes, you can, but you should not. The whole purpose of the ViewModel is to separate the logic into its own class rather than having it intermixed with view code.

Instead use the INotifyPropertyChanged interface to notify the UI that the image source has changed. If possible try to see if you can use a regular binding for the value you want to use, that will be the most robust and most easy way.

Another solution is to expose a interface on the view. Something like IView, you can probably come up with a more suitable name like IResetable.

interface IResetable
{
    void Reset();
}
class MainWindow: Window, IResetable
{
    publiv void Reset()
    {
        // Here you can access the view, but try to keep logic minimal.
    }
}    
class ViewModel
{
    private readonly IResetable resetable;
    public ViewModel(IResetable resetable)
    {
         _resetable = resetable;
    }
    void Foobar()        
    {
         _resetable.Reset();
    }

}

Upvotes: 1

Related Questions