2012-08-09 66 views
1

我想創建一個具有內容控件的用戶控件,該內容控件將其內容綁定到一個依賴對象。代碼如下所示使用xaml來定義用戶控件和綁定數據的內容

的XAML

<ContentControl Grid.Column="1" HorizontalAlignment="Stretch" x:Name="NotifyContent" Content="{Binding ElementName=notifyBarCtrl, Path=Content, NotifyOnSourceUpdated=True}" /> 

C#

public object Content 
{ 
    get { return (object)GetValue(ContentProperty); } 
    set { SetValue(ContentProperty, value); } 
} 

// Using a DependencyProperty as the backing store for Content. This enables animation, styling, binding, etc... 
public static readonly DependencyProperty ContentProperty = 
    DependencyProperty.Register("Content", typeof(object), typeof(NotifyBar)); 

我遇到的問題是,當我嘗試使用XAML來定義的內容以文本塊,然後綁定文本屬性到我的應用程序中的一個字符串,它在字符串更改時無法更新:

我的應用程序代碼如下

的XAML

<ctrl:NotifyBar DockPanel.Dock="Top" Background="White" HorizontalAlignment="Stretch" > 
    <ctrl:NotifyBar.Content> 
     <TextBlock Height="30" Text="{Binding ElementName=MainWindow, Path=NotifyMessage, Mode=TwoWay}" HorizontalAlignment="Stretch" /> 
    </ctrl:NotifyBar.Content> 
</ctrl:NotifyBar> 

C#

public string NotifyMessage 
    { 
     get { return _NotifyMessage; } 
     set 
     { 
      if (_NotifyMessage != value) 
      { 
       _NotifyMessage = value; 
       OnPropertyChanged("NotifyMessage"); 
      } 
     } 
    } 

任何建議,我可能會丟失或可能做錯了,將不勝感激。

感謝

[編輯]

因爲我已經改變了內容扶養屬性NotifyContent因爲我得到一個警告,這是壓倒一切的內容以用戶控件,但這仍然未解決的問題

回答

0

所以我想通了,這是因爲我在文本塊中使用elementname。

如果我將usercontrol的DataContext設置爲元素並綁定到propertiesit工作。

見下圖:

<ctrl:NotifyBar DataContext="{Binding ElementName=MainWindow}" DockPanel.Dock="Top" Background="White" HorizontalAlignment="Stretch" > 
    <ctrl:NotifyBar.Content> 
     <TextBlock Height="30" Text="{Binding Path=NotifyMessage, Mode=TwoWay}" HorizontalAlignment="Stretch" /> 
    </ctrl:NotifyBar.Content> 
</ctrl:NotifyBar>