2010-03-16 163 views
0

主窗口依赖属性格式绑定问题

<Window x:Class="dep2.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:dep2" 
    Title="Window1" Height="300" Width="381"> 
    <Grid> 
     <local:UserControl1></local:UserControl1> 
     <Button Height="23" HorizontalAlignment="Right" Margin="0,0,77,36" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click">Button</Button> 
    </Grid> 
</Window> 

public partial class Window1 : Window 
{ 
    UserControl1 uc = new UserControl1(); 
    public Window1() 
    { 
     InitializeComponent(); 

    } 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     uc.InfoText = "SAMPLE"; 
    } 
} 

我的用户控件

<UserControl x:Class="dep2.UserControl1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Height="32" Width="300"> 
    <Grid Height="30"> 
     <StackPanel Background="LightCyan"> 
      <TextBox Height="21" Name="textBlock1" Width="120" Text="{Binding Text}" /> 
     </StackPanel> 


    </Grid> 
</UserControl> 



public partial class UserControl1 : UserControl 
{ 
    public string InfoText 
    { 
     get 
     { 
      return (string)GetValue(InfoTextProperty); 
     } 
     set 
     { 
      SetValue(InfoTextProperty, value); 
     } 
    } 

    public static readonly DependencyProperty InfoTextProperty = 
     DependencyProperty.Register(
      "InfoText", 
      typeof(string), 
      typeof(UserControl1), 
      new FrameworkPropertyMetadata(
      new PropertyChangedCallback(ChangeText))); 

    private static void ChangeText(DependencyObject source, DependencyPropertyChangedEventArgs e) 
    { 
     (source as UserControl1).UpdateText(e.NewValue.ToString()); 
    } 

    private void UpdateText(string NewText) 
    { 

     textBox1.Text = NewText; 

    } 


    public UserControl1() 
    { 
     InitializeComponent(); 
     DataContext = this; 


    } 
} 

我得到我的用户控件依赖属性值,但我不能能我值绑定到文本box.am像这样绑定Text =“{Binding Text}”是否正确,或者如何在用户控件中绑定我的值

我附上我的示例项目, http://cid-08ec3041618e8ee4.skydrive.live.com/self.aspx/.SharedFavorites/dep2.rar

任何一眼能告诉什么是错在,

everythng运作良好,但我不能绑定在文本框中的值,

当u单击该按钮可以看出U传递的价值用户控件在消息框中,但我不能在文本框中绑定该值。

为什么?

+2

在您的问题中包含相关代码会更好。 (几乎)没有人会下载你的整个项目,寻找相关的部分,然后尝试找到问题。保持链接在那里,但另外提供相关的代码部分! – gehho

+0

@gehho,我完全同意你的看法。我决定给它最多30秒。 – Timores

+0

@deepak,我只是因为你是新来的。请遵循gehho的未来建议。 – Timores

回答

2

您的代码处理来自依赖项属性的回调并直接设置文本框的值。这不是这个回调的作用。

而通过设置Text属性,你已经失去了绑定。本地属性设置的优先级高于绑定。请参阅this blog