绑定到usercontrol无法正常工作

时间:2012-02-11 12:57:14

标签: wpf data-binding user-controls

我遇到了数据绑定问题, 所以我创建了一个usercontrole

UserControl1.xaml.cs

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }
    public static DependencyProperty TestThisProperty = DependencyProperty.Register
        (
        "TestThis",
        typeof(string),
        typeof(UserControl1),
        new PropertyMetadata("Some Data",new PropertyChangedCallback(textChangedCallBack))
        );
    public string TestThis
    {
        get { return (string)GetValue(TestThisProperty); }
        set { SetValue(TestThisProperty, value); }
    }
    static void textChangedCallBack(DependencyObject property, DependencyPropertyChangedEventArgs args)
    {
        UserControl1 _us = (UserControl1)property;

        _us.MyUserControl.TestThis = (string)args.NewValue;

    }
}

UserControl1.xaml

<UserControl x:Class="WpfApplication1.UserControl1"
         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"  x:Name="MyUserControl"

         d:DesignHeight="300" d:DesignWidth="300">
          </UserControl>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    UserControl1 _uc = new UserControl1();

    public MainWindow()
    {
        InitializeComponent();
        DispatcherTimer _dt = new DispatcherTimer();
        _dt.Interval = new TimeSpan(0, 0, 1);
        _dt.Start();
        _dt.Tick += new EventHandler(_dt_Tick);
    }
    private void _dt_Tick(object s,EventArgs e)
    {
        _uc.TestThis = DateTime.Now.ToString("hh:mm:ss");

    }

最后是MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">

<Grid>
    <TextBox Text="{Binding Path=TestThis,ElementName=MyUserControl, UpdateSourceTrigger=PropertyChanged}"/>

  </Grid>

但问题在这里,当我调试我的代码时,我得到了这个警告 找不到引用'ElementName = MyUserControl'的绑定源。并且ui当然没有更新,有什么想法吗?

1 个答案:

答案 0 :(得分:3)

ElementName仅针对同一namescope中的名称,例如

<TextBox Name="tb"/>
<Button Content="{Binding Text, ElementName=tb}"/>

如果你没有在MainWindow XAML中定义UserControl并在那里给它起一个名字,或者在代码后面register a name(并将其作为目标),你就不会得到这个ElementName绑定工作。

另一种方法是将usercontrol作为MainWindow上的属性公开,例如

public UserControl1 UC { get { return _uc; } }

然后你可以像这样绑定:

{Binding UC.TestThis, RelativeSource={RelativeSource AncestorType=Window}}