tags:

views:

20

answers:

1

Hi,

I have one user control in wpf. And I want to use this user control two times in same view.

I am using mvvm approach. Can anybody give me a good suggestion that what approach I should follow.

+1  A: 

Um, any reason why you aren't just using it twice? If you bind to the VM (as the DataContext) with the same properties, it will "just work," no differently than binding two TextBlocks (or other "regular" control) to the same property in the VM.

Here I use the same control in the same window, but it could just as easily be used in the same UserControl, DataTemplate, etc. - whatever you are defining as a "view".

XAML

<Window x:Class="MyNamespace.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyNamespace"
        Title="My Window" Width="300" Height="300">
    <StackPanel>
        <local:MyUserControl x:Name="control1" 
                             SomeProperty="{Binding MyMVVMProperty}" />
        <local:MyUserControl x:Name="control2" 
                             SomeProperty="{Binding MyMVVMProperty}" />

        <TextBlock x:Name="txt1"
                   Text="{Binding AnotherMVVMProperty}" />
        <TextBlock x:Name="txt2"
                   Text="{Binding AnotherMVVMProperty}" />
        <TextBlock x:Name="txt3"
                   Text="{Binding AThirdMVVMProperty}" />

    </StackPanel>
</Window>

Code Behind

class Window1 : Window
{
    MyViewModel mViewModel = new MyViewModel();

    public Window1()
    {
        this.DataContext = mViewModel;
    }
}
Wonko the Sane
But ..the issue is...Lets think my user control is a grid. when i select an item in one user control...the same item will be selected in other.
Anish
Exactly. That's what MVVM is. If you use the same control with the same properties, the same thing should happen in both. If you use the same control but change a different property, something different should happen. I've updated my answer above - I added a third TextBlock. txt1 and txt2 bind to the same property, so if AnotherMVVMProperty changes, both should reflect that. However, txt3 (which is also an instance of a TextBlock control) binds to a completely different value, and won't be affected by a change to the AnotherMVVMProperty.
Wonko the Sane
Another way to look at it is this - you could put two ListBoxes on a View, and bind it to your ViewModel. If they both bind to the same collection property in your VM, they will be the same; if they bind to different properties, they will be different. A UserControl is no different than any other control, if it is using Binding and not hard-coded values.
Wonko the Sane
I do agreee with you. But when I tried it, the result was not like this. I ll check it again. Thanks.
Anish