wpf从主窗口文本框中绑定usercontrol文本框内的文本

时间:2014-01-08 05:55:12

标签: c# asp.net wpf silverlight mvvm

主窗口

<TextBox x:Name="fbSearchBox" Margin="69,10,298,11" TextWrapping="Wrap" BorderBrush=" x:Null}"/>
<local:FacebookAutoComplete "want to set text from here of fbSearchBox" />

用户控制

<UserControl x:Class="ZuneWithCtrls.Pages.Facebook.Home.FacebookAutoComplete"
         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" 
         d:DesignHeight="300" d:DesignWidth="300" Width="431" Height="49"
         x:Name="uc">
<TextBlock x:Name="txtDynamicText"/>

</UserControl>

当从fbSearchBox中输入时,想要在txtdynamicText中显示文本.Plz help

1 个答案:

答案 0 :(得分:4)

您需要绑定到用户控件中的某些属性。
向用户控件添加依赖项属性:

    public static readonly DependencyProperty DynamicTextProperty =
       DependencyProperty.Register(
          "DynamicText",
          typeof(string),
          typeof(FacebookAutoComplete),
          new FrameworkPropertyMetadata(null));

    public string DynamicText
    {
        get { return (string)GetValue(DynamicTextProperty); }
        set { SetValue(DynamicTextProperty, value); }
    }

将用户控件内的嵌套控件绑定到此依赖项属性:

<TextBlock x:Name="txtDynamicText" 
           Text="{Binding Path=DynamicText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>

现在,您可以将FacebookAutoComplete.DynamicText绑定到TextBox的{​​{1}}:

MainWindow