c#中的简单依赖属性和UserControl问题

本文关键字:UserControl 问题 属性 依赖 简单 | 更新日期: 2023-09-27 17:50:30

我的最终目标是公开TextBoxText值,我在UserControl中有UserControl在XAML中的调用。

<my:UserControl SetCustomText="Blah blah this is variable">

将显示UserControlTextBox的文本。

我一直在使用各种例子来工作,但我总是以"属性SetCustomText在类型UserControl中未找到"结束

c#中的简单依赖属性和UserControl问题

示例:

<UserControl x:Class="Test.UserControls.MyUserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             Name="control">
    <Grid>
        <!-- Text is being bound to outward representative property -->
        <TextBox Text="{Binding MyTextProperty, ElementName=control}"/>
    </Grid>
</UserControl>
public partial class MyUserControl1 : UserControl
{
    // The dependency property which will be accessible on the UserControl
    public static readonly DependencyProperty MyTextPropertyProperty =
        DependencyProperty.Register("MyTextProperty", typeof(string), typeof(MyUserControl1), new UIPropertyMetadata(String.Empty));
    public string MyTextProperty
    {
        get { return (string)GetValue(MyTextPropertyProperty); }
        set { SetValue(MyTextPropertyProperty, value); }
    }
    public MyUserControl1()
    {
        InitializeComponent();
    }
}
<uc:MyUserControl1 MyTextProperty="Text goes here"/>