c# - XAML:访问用户控件内的控件

标签 c# silverlight xaml windows-phone

我有这样的用户控件:

<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/

相关文章:

Silverlight MVVM 绑定(bind)和扩展类属性的使用

xaml - 让 ListView 滚动到所选项目

wpf - 如何使滚动查看器在 WPF 中将高度设置为自动的情况下工作?

c# - 从 NHibernate 子查询中仅选择某些属性

c# - 在 Xamarin 项目中隐藏 Azure 凭据和连接字符串的最佳方法

c# - 如何通过反射获得诸如 `new()` 的约束。 ()

wpf - Silverlight 3 中 ItemContainerStyle 中的数据绑定(bind)问题

c# - INotifyPropertyChanged 绑定(bind)未按预期更新

c# - Windows Phone 上的 WriteableBitmap 高速绘图

c# - 选择 y 表中的所有 x