开发者

Implementing commands in MMVM

I am trying to change the source property of the frame in Page1.xaml when the SampleCommand is excecuted. How do I acheive this in the View Model?

Page1.xaml:

<Page ...>
<DockPanel>
    <r:ribbon>         
        <r:RibbonTab Label="Keys">
            <r:RibbonTab.Groups>
                <r:RibbonGroup GroupSizeDefinitions="{StaticResource RibbonLayout}">
                    <r:RibbonGroup.Command>
                        <r:RibbonCommand LabelTitle="RibbonButton"/>
                    </r:RibbonGroup.Command>
                    <r:RibbonButton x:Name="RibbonButton1" Command="{Binding Path=SampleCommand}"/>
                </r:RibbonGroup>
            </r:RibbonTab.Groups>
        </r:RibbonTab>
    </r:Ribbon>

 开发者_如何学JAVA   <Border Name="PageBorder" Grid.Row="0" Grid.Column="1">
        <Frame Name="pageFrame" Source="FirstPage.xaml" />

    </Border>
</DockPanel>
</Page>

Page1ViewModel.cs:

RelayCommand _sampleCommand;

public ICommand SampleCommand
{
    get
    {
        // create command ??

        return _sampleCommand 
    }
}

page1.xaml.cs:

Page1ViewModel pageViewModel;

//When page loads

this.DataContext = pageViewModel;


Depending on whose implementation of RelayCommand you're using, it should take an Action as a parameter to its constructor which represents the code to be called when it's implemented. So in your ViewModel:

_sampleComand = new RelayCommand(() => DoStuff());

The thing here, though, is that you want to call Navigate on your "pageFrame" control, which the ViewModel won't have access to.

Probably the easiest way to get around that is to pass the Frame's NavigationService to the command as a parameter. You might need to change the declaration of _sampleCommand so that it knows it takes a parameter; some implementations of RelayCommand also define a RelayCommand<T> which is a command that accepts a strongly-typed parameter.

private ICommand _sampleCommand;
...
_sampleCommand = new RelayCommand<NavigationService>(
    ns => ns.Navigate(destinationUri));

So now you need to pass the frame's NavigationService to the command:

<r:RibbonButton x:Name="RibbonButton1" 
                Command="{Binding Path=SampleCommand}"
                CommandParameter="{Binding NavigationService,ElementName=pageFrame}"
                />

Since your ViewModel is probably going to have a whole bunch of navigation commands, it's probably easier to set up a property of type NavigationService on the ViewModel itself and have the page hook it up to its frame when you initialize things. That way you can reference that property rather than passing it in as a command parameter every time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜