2012-08-09 76 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>