2010-02-15 68 views
1

我无法得到以下场景工作(此代码不是实际的代码,但主体是相同的。基本上我需要从一个MainPage向下传递一个值到一个嵌套的“可重用的用户控制“,它绑定到它自己的属性我想看到”This is it!“文本在屏幕上,但它没有被设置在SilverlightControl2控件(我怀疑由于DataContext的设置) - 但我怎么解决这个问题?UserControls的嵌套绑定

MainPage.xaml中

<Grid> 
    <ContentPresenter> 
     <ContentPresenter.Content> 
      <Local:SilverlightControl1 OneValue="This is it!"/> 
     </ContentPresenter.Content> 
    </ContentPresenter> 
</Grid> 

SilverlightControl1.xaml

<Grid> 
    <Local:SilverlightControl2 TwoValue="{Binding OneValue}"/> 
</Grid> 

SilverlightControl1.xaml.cs

public partial class SilverlightControl1 : UserControl 
{ 
    public string OneValue 
    { 
     get { return (string)GetValue(OneValueProperty); } 
     set { SetValue(OneValueProperty, value); } 
    } 

    public static readonly DependencyProperty OneValueProperty = DependencyProperty.Register(
     "OneValue", typeof(string), typeof(SilverlightControl1), new PropertyMetadata(string.Empty)); 

    public SilverlightControl1() 
    { 
     InitializeComponent(); 
     this.DataContext = this; 
    } 
} 

SilverlightControl2.xaml

<Grid x:Name="LayoutRoot" Background="White"> 
    <TextBlock Text="{Binding TwoValue}" Foreground="Blue" /> 
</Grid> 

SilverlightControl2.xaml.cs

public partial class SilverlightControl2 : UserControl 
{ 
    public string TwoValue 
    { 
     get { return (string)GetValue(TwoValueProperty); } 
     set { SetValue(TwoValueProperty, value); } 
    } 

    public static readonly DependencyProperty TwoValueProperty = DependencyProperty.Register(
     "TwoValue", typeof(string), typeof(SilverlightControl2), new PropertyMetadata(string.Empty)); 


    public SilverlightControl2() 
    { 
     InitializeComponent(); 
     this.DataContext = this; 
    } 
} 

回答

1

只要你发现自己的感觉,需要做这个: -

this.DataContext = this; 

知道你可能有错误。它可能是我期望在Silverlight特定的“难闻气味列表”中找到的第一件事。

在这种情况下,你是专业UserControl更好的方法是做到这一点: -

SilverlightControl1.xaml

<Grid>   
    <Local:SilverlightControl2 x:Name="MyControl2" />   
</Grid> 

SilverlightControl1.xaml.cs(我只是展示构造休息是因为你拥有它)

public SilverlightControl1() 
{ 
    InitializeComponent(); 
    MyControl2.SetBinding(SilverlightControl2.TwoValueProperty , new Binding("OneValue") { Source = this }); 

} 

SilverlightControl2.xaml

<Grid x:Name="LayoutRoot" Background="White">    
    <TextBlock x:Name="MyTextBox" Foreground="Blue" />    
</Grid> 

SilverlightControl1.xaml.cs(我只是展示构造函数的其余部分是因为你拥有它)

public SilverlightControl2() 
{ 
    InitializeComponent(); 
    MyTextBox.SetBinding(TextBox.TextProperty , new Binding("TwoValue") { Source = this }); 
} 

由于UserControls你知道XAML的结构,你可以命名元素您需要在代码中访问,您可以使用一行代码来创建绑定。 这使得DataContext可以自由地完成设计的任务,而不是为了不同的目的而高枕无忧。

,其中,代替专业UserControl您创建一个模板控制,在这种情况下,结合可以在XAML使用的东西来表达类似的另一种方法: -

<TextBox Text="{TemplateBinding TwoValue}" /> 

模板绑定只在ControlTemplate这样你就可以工作”不要在UserControl中使用它。