2010-11-30 70 views
0

更新這裏是我的問題的再現:的DependencyProperty在用戶控件沒有得到來自結合

  • 創建一個WPF應用程序
  • 添加一個新的用戶控件到項目
  • 用以下內容替換其內容

<UserControl 
    x:Class="UserControl1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    DataContext="{Binding RelativeSource={RelativeSource Self}}"> 
    <TextBlock Text="{Binding MyText}"/> 
</UserControl> 

Public Class UserControl1 
    Public Property MyText As String 
    Get 
     Return GetValue(MyTextProperty) 
    End Get 
    Set(ByVal value As String) 
     SetValue(MyTextProperty, value) 
    End Set 
    End Property 
    Public Shared ReadOnly MyTextProperty As DependencyProperty = 
    DependencyProperty.Register("MyText", GetType(String), GetType(UserControl1)) 
End Class 
  • 替換的MainWindow.xaml文件中的以下內容:

<Window 
    x:Class="MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:src="clr-namespace:WpfApplication1" 
    Title="MainWindow" 
    DataContext="{Binding RelativeSource={RelativeSource Self}}"> 
    <StackPanel >  
    <TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}"/> 
    <src:UserControl1 MyText="{Binding Title}"/> 
    </StackPanel> 
</Window> 

正如你所看到的,UserControl1.MyText財產沒有更新的主窗口時。標題更改。

我錯過了什麼?我想要用戶控件連接到父項屬性,是否有一種xamly的方式來做到這一點?

回答

2

好吧,當我重新創建應用程序(我使用C#,所以我不認爲這會有所作爲),我注意到在我的輸出中綁定失敗,因爲UserControl沒有Title屬性。

ElementName=this添加到您的UserControl1綁定。並將窗口上的名稱屬性設置爲此,並應該修復它。

事情是這樣的:

<src:UserControl1 MyText="{Binding Title, ElementName=this}" /> 

對我來說,綁定工作,當我做到這一點。希望有所幫助!

+0

你是男人。 – Shimmy 2010-11-30 17:57:12

相關問題