我有这样的用户控件:
<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>
我在另一个 XAML 中使用此 userControl,如下所示:
<MyControlls:MyButton Width="90" Height="55"/>
现在如何访问此 XAML 中名为 Text 的文本 block 并更改其文本(在 Windows Phone 8 中)? 像这样:
<MyControlls:MyButton Width="90" Height="55">
<MyButton.Text Text="Hello World!" />
</MyControlls:MyButton>`
谢谢。
最佳答案
我找到了解决方案。
<UserControl x:Class="Becel.Controls.MyButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
x:Name="MyUserControll">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Image x:Name="myImage" Source="/Images/btn1.9_normal@2x.png" Stretch="Fill"
MouseEnter="Image_MouseEnter" MouseLeave="Image_MouseLeave" />
<TextBlock x:Name="textTitle" Text="{Binding Title, ElementName=MyUserControll}" VerticalAlignment="Center" HorizontalAlignment="Center" TextAlignment="Center" Foreground="Black" FontSize="25" MouseEnter="Image_MouseEnter" MouseLeave="Image_MouseLeave"/>
</Grid>
</UserControl>
在 C# 代码中:
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof (String), typeof(MyButton),null);
public String Title
{
get { return (String)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
然后在任何地方你都可以这样使用:
<MyUserControl:MyButton Width="90" Height="55" Margin="10 0 0 0" Title="Hello Wold!" />
关于c# - XAML:访问用户控件内的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19491951/