0

我创建了 userControl,其中有两个文本块。我可以在 xaml 页面上设置文本以使用此代码。

    <my:Title Title  TitleCaption="test On XMAL"   />

但是我想在代码上设置文本的值。有人会告诉我如何完成这项任务吗?提前致谢。

有我的用户控件:

<UserControl x:Name="TitleSection"  x:Class="CMSPhoneApp.Title"
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}"
d:DesignHeight="480" d:DesignWidth="480">


<Grid x:Name="LayoutRoot" Style="{StaticResource GridTitleStyle1}" >

    <StackPanel>
    <TextBlock  x:Name="ApplictionTtile" Width="350" Text="MyAppTitle " HorizontalAlignment="Left" FontSize="20">
        <TextBlock.Foreground>
            <SolidColorBrush Color="#FFFFFF"/>
        </TextBlock.Foreground>
    </TextBlock>
        <TextBlock   x:Name="PageTtile"  Style="{StaticResource TitleTextBlockStyle}" 
               Text="{Binding Path=TitleCaption, Mode=TwoWay,  ElementName=TitleSection }"      
                     >


         </TextBlock>
    </StackPanel>
</Grid>

以下是此页面背后的代码:

namespace CMSPhoneApp
{
    public partial class Title : UserControl
    {
    public Title()
    {
        InitializeComponent();
    }

    public static DependencyProperty TitleCaptionProperty =
 DependencyProperty.Register("TitleCaption", typeof(string), typeof(Title), null);

    public string TitleCaption
    {
        get
        {
            return (string)GetValue(TitleCaptionProperty);
        }
        set
        {
            SetValue(TitleCaptionProperty, value);
        }
    }
}

}

4

2 回答 2

1

It can be done in a much easier way, your property should be:

public string TitleCaption
    {
        get
        {
            return PageTitle.Text;
        }
        set
        {
            PageTitle.Text=value;
        }
    }

Now when you create the control name it:

<my:Title Name="myTitle"  TitleCaption="test On XMAL"   />

Now you can change PageTitle from code by the following code:

myTitle.TitleCaption="your Text Goes Here";
于 2012-07-10T05:23:25.377 回答
0

从代码中,您可以执行以下操作:

PageTtile.Text = "This is from code"; // where PageTile is the x:Name of the TextBlock in XAML
于 2012-07-09T22:54:16.697 回答