2011-04-18 48 views
1

我的最終目標是揭示的值,我在UserControl中使用了,這個值來自UserControl在XAML中的調用。C#中簡單的依賴項屬性和用戶控制問題

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

將在提交該TextBox的文本渲染UserControl

我在它用各種例子已經工作,但我總是落得「該物業SetCustomText不是在用戶控件類型發現「你如何能做到這

+0

請張貼代碼爲SetCustomText依賴屬性? – 2011-04-18 05:39:06

+0

這是公共財產嗎? – V4Vendetta 2011-04-18 05:44:44

+0

你確定它的正確UserControl?我不會將您的自定義類命名爲WPF中的相同名稱。它令人困惑。 – Euphoric 2011-04-18 06:20:28

回答

2

例子:

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

如果我們在用戶控件上有兩個文本塊呢? – 2014-09-02 06:05:12

+0

@HamedZakeryMiab然後使用兩個名稱和兩個依賴屬性。那有多難? – ProfK 2017-02-01 12:23:11