I have userControl like this:
<Grid x:Name="LayoutRoot" Background="Transparent">
<Image Source="/Images/btn1_normal@2x.png" Stretch="Fill" />
<TextBlock x:Name="Text" Text="Button" Foreground="Black"
VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Grid>
I use this userControl in another XAML like this:
<MyControlls:MyButton Width="90" Height="55"/>
Now how I can access to textBlock named Text in this XAML and change his text (in Windows phone 8)? Something like this:
<MyControlls:MyButton Width="90" Height="55">
<MyButton.Text Text="Hello World!" />
</MyControlls:MyButton>`
Thank You.
I found the solution.
And in C# code :
And then in everywhere you can use like this:
To achieve this task, one solution could be to declare a Dependency Property into your
Control
(which seems to be called "MyButton") code behind :Then you have to bind to it into your xaml code :
Finally, you are able to use your "MyButton"
Control
:You can't do that directly. Here are two alternatives.
Solution 1 : use a ViewModel
Use a view model class to store the properties that you need to display in your custom control.
MyButton.xaml:
MainWindow.xaml
This use the MVVM pattern. See WPF Apps With The Model-View-ViewModel Design Pattern, if you never used it.
Solution 2 : use a CustomControl
Replace your
UserControl
by aCustomControl
. In that caseText
can be a dependency property, so that you can write.This is much more complex. See How to Create a WPF Custom Control.
Which to choose ?
If you intend to use your control in several different projects, and you need to be able to change the skin of the control, choose the
UserControl
.Otherwise, go for the
ViewModel
and eventually apply the MVVM pattern in the remaining off your project.