Simple Dependency Property and UserControl issues in C#

ぃ、小莉子 提交于 2019-12-29 01:44:13

问题


My end goal is to expose the Text value of a TextBox that I have in a UserControl, from the UserControl's call in XAML.

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

would render the UserControl with that TextBox's text filed in.

I've been working at it using various examples but I always end up with "The Property SetCustomText was not found in type UserControl"


回答1:


Example of how you can do this:

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


来源:https://stackoverflow.com/questions/5698865/simple-dependency-property-and-usercontrol-issues-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!