Yes! it seems a duplicate topic is about to start. This is because I couldn't find an explicit answer after many searches!!! So I try to describe the story as clear as possible. (Sorry for verbiage)
I have a UserControl named CUC (stands for Child User-Control) with some Dependency Properties (DPs) in its code-behind. These DPs are participated in the XAML file.
e.g.
<TextBlock Text="{Binding Title}" Background="{Binding TitleBackground}"/>
where Title& TitleBackground are DPs in code-behind. As usual, I setDataContext of root element to the UC, itself!
public CUC() { InitializeComponent(); layoutRoot.DataContext = this; }
Okay?
- Of course not!!! UI is not data! MVVM said :)
So... I wanna re-create this UC in the MVVM pattern. It's easy! I should define a new class called CUCViewModel and move the above mentioned DPs in it. Then it's enough to set this class as the CUCDataContext. Over! So far so good.
<v:CUC><v:CUC.DataContext><vm:CUCViewModel /></v:CUC.DataContext></v:CUC>
Now, assume there is another UC called PUC (stands for Parent User-Control). This UC is supposed to be parent of CUC and control its TitleBackground property. In this scenario, there are two or more instances of CUC in the PUC. Every CUC instance has an arbitrary Title. (It's constant.) For example they are "Title1", "Title2", etc. Also, PUC has a property of type string, called AllTitlesBackgrounds. As you guess, this property value should be set to all CUC instances TitleBackground. Okay?
Now, I have some questions:
1. How can I set Title property of CUC instances in the PUC? e.g.
<StackPanel><v:CUC><v:CUC.DataContext><vm:CUCViewModel Title="Title1"/></v:CUC.DataContext></v:CUC><v:CUC><v:CUC.DataContext><vm:CUCViewModel Title="Title2"/></v:CUC.DataContext></v:CUC> ∙∙∙ </StackPanel>
Is this correct?
2. How PUC can control TitleBackground property of CUC instances?
<StackPanel><v:CUC><v:CUC.DataContext><vm:CUCViewModel Title="Title1" TitleBackground="{Binding AllTitleBackgrounds}"/></v:CUC.DataContext></v:CUC><v:CUC><v:CUC.DataContext><vm:CUCViewModel Title="Title2" TitleBackground="{Binding AllTitleBackgrounds}"/></v:CUC.DataContext></v:CUC> ∙∙∙ </StackPanel>
(The above code doesn't work.)
Thanks in advance