2011-12-28 81 views
1

我正在創建一個自定義用戶控件。它有兩個我想綁定到Properties的DependencyProperties。當我使用我的用戶,做它拋出一個異常綁定:在自定義用戶控件中綁定到DependencyProperties會拋出異常

System.Windows.Markup.XamlParseException:

「A‘綁定’不能對類型的「的‘的PropertyValue’屬性設置AgentPropertyControl 」 A‘綁定’只能在DependencyObject的一個DependencyProperty設置

我想不出什麼我做錯了

這是我的用戶XAML代碼:。

<UserControl x:Class="AgentProperty.AgentPropertyControl" 
      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" 
      mc:Ignorable="d" 
      d:DesignHeight="26" d:DesignWidth="288" 
      x:Name="MyUserControl"> 
    <Grid Name="grid"> 
     <StackPanel Orientation="Horizontal"> 
      <Label Name="lblPropertyTitle" Width="100" Margin="2" FontWeight="Bold" VerticalAlignment="Center"/> 
      <TextBox Name="tbPropertyValue" Width="150" Margin="2" VerticalAlignment="Center"/> 
     </StackPanel> 
    </Grid> 
</UserControl> 

的綁定在代碼隱藏設置:

public partial class AgentPropertyControl : UserControl 
{ 
    public readonly static DependencyProperty PropertyTitleDP = DependencyProperty.Register("PropertyTitle", typeof(string), typeof(Label), new FrameworkPropertyMetadata("no data")); 
    public readonly static DependencyProperty PropertyValueDP = DependencyProperty.Register("PropertyValue", typeof(string), typeof(TextBox), new FrameworkPropertyMetadata("no data")); 

    public string PropertyTitle 
    { 
     set { SetValue(PropertyTitleDP, value); } 
     get { return (string) GetValue(PropertyTitleDP); } 
    } 

    public string PropertyValue 
    { 
     set { SetValue(PropertyValueDP, value); } 
     get { return (string)GetValue(PropertyValueDP); } 
    } 

    public AgentPropertyControl() 
    { 
     InitializeComponent(); 

     lblPropertyTitle.SetBinding(Label.ContentProperty, new Binding() {Source = this, Path = new PropertyPath("PropertyTitle")}); 
     tbPropertyValue.SetBinding(TextBox.TextProperty, new Binding() { Source = this, Path = new PropertyPath("PropertyValue"), Mode = BindingMode.TwoWay }); 
    } 
} 

而且我的用戶的使用:

<AgentProperty:AgentPropertyControl PropertyTitle="ID" PropertyValue="{Binding Path=ID}" Grid.ColumnSpan="2"/> 

其DataContext設置在包含用戶控件的網格。

爲什麼拋出異常,我該如何解決?

回答

2

DependencyProperty.Register的第三個參數是所有者類型。在你的情況下,它應該是你的控制:

public readonly static DependencyProperty PropertyTitleDP = DependencyProperty.Register("PropertyTitle", typeof(string), typeof(AgentPropertyControl), new FrameworkPropertyMetadata("no data")); 
public readonly static DependencyProperty PropertyValueDP = DependencyProperty.Register("PropertyValue", typeof(string), typeof(AgentPropertyControl), new FrameworkPropertyMetadata("no data")); 
+0

謝謝!這解決了問題:) – 2011-12-28 09:50:05

相關問題