2010-03-16 165 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