wpf – same two user control in xaml – Education Career Blog

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.

,

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;
    }
}

Leave a Comment