开发者

Silverlight UserControl in MVVM with RelayCommand<T> - example?

Has somebody a good example to create a UserControl, and then bind commands to it?

My problem is to forward the command to a control in the UserControl, for example to a TreeView's Drop event. It's not clear, how can I do that.


Both answer are interesting and thanks, they help, but...

I want something like that:

The usage:

<my:MyControl Command="{Binding XCommand}" CommandParameter="{Binding [Here what?]}"/>

The control contains the two DependencyProperties, Command and CommandPa开发者_开发知识库rameters, and I'd like to bind these two DependecyProperties to a TreeView - Drop event. How can I do that? Because the usage of the CommandParameter is reversed: not the control passes a parameter, but the users wants something: CommandParameter="{Binding Text, ElementName=DisableCommandTextBox}"


You are trying to forward an event to your viewmodel. I guess you don't need RelayCommand but you will need EventToCommand. I don't know about binding the treeview events, but you can always give it a try.

Example using MVVM Light: http://geekswithblogs.net/lbugnion/archive/2009/11/05/mvvm-light-toolkit-v3-alpha-2-eventtocommand-behavior.aspx

<Rectangle Fill="White"
           Stroke="Black"
           Width="200"
           Height="100">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseEnter">
            <cmd:EventToCommand Command="{Binding TestCommand,
                                          Mode=OneWay}"
               CommandParameter="{Binding Text,
                                  ElementName=MyTextBox,
                                  Mode=OneWay}"
               MustToggleIsEnabledValue="True" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Rectangle>


Unfortunately, we cannot bind a RelayCommand within a viewmodel directly to the Drop event due to the limitations on TreeView.

However, this problem has been previously solved. Take a look at this link to see how it was done. If you'd like an example of a more typical command binding (to a button perhaps), leave a comment below and I'll add that in.


I just had to leave the CommandParameter, and I call the command in the SelectedItemChanged event handler with the appropiate parameter.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜