开发者

DependencyProperty in UserControl doesn't get updated from binding

Here is the reproduction of my problem:

  • Create a WPF Application
  • Add a new UserControl to the project
  • Replace its content with the following

<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
  • Replace the following in the MainWindow.xaml file:

<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>

As you can see, the UserControl1.MyText property doesn't get updated when the MainWindow.Title changes.

What am I missing? I want the user control to be connected to the parent property, is there a xamly way to do it?


Okay, when I recreate the app (I'm using C#, so I don't think this will make any difference), I notice in my output the binding is failing because UserControl does not have a Title property.

Add ElementName=this to your UserControl1 binding. And set the Name property on the Window to this and that should fix it.

Something like this:

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

The binding works for me when I do that. Hope that helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜