C#中的简单依赖属性和用户控件问题

3

我的最终目标是从XAML中调用UserControl时,暴露在UserControl中的TextBoxText值。

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

使用该方法会将UserControl与该TextBox的文本字段一起呈现。

我一直在尝试使用各种示例进行工作,但最终都出现了“在UserControl类型中未找到Property SetCustomText”的错误。


请发布 SetCustomText 依赖属性的代码? - Kishore Kumar
你确定这是正确的 UserControl 吗?我不会给你的自定义类起与 WPF 中某个名称相同的名字,那样会令人困惑。 - Euphoric
1个回答

4

以下是如何做到这一点的示例:

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

如果用户控件上有两个文本块怎么办? - Hamed Zakery Miab
@HamedZakeryMiab 然后使用两个名称和两个依赖属性。这有多难? - ProfK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接