2012-10-20 33 views
1

我有綁定到我的依賴項新控件的屬性問題。
我決定寫一些測試來研究這個問題。
綁定到的DependencyProperty沒有結果

從TextBox.Text綁定到另一個TextBox.Text

XAML代碼:

<TextBox Name="Test" Text="{Binding ElementName=Test2, Path=Text, UpdateSourceTrigger=PropertyChanged}" /> 
<TextBox Name="Test2" Grid.Row="2" /> 

結果是好 - 當我在寫第一個TextBox的東西 - >第二個文本框正在更新(相反也是)。

enter image description here

我創造了新的控制 - >例如 「SuperTextBox」 與依賴屬性 「SuperValue」。

控制XAML代碼:

<UserControl x:Class="WpfApplication2.SuperTextBox" 
      ... 
      Name="Root"> 
    <TextBox Text="{Binding SuperValue, ElementName=Root, UpdateSourceTrigger=PropertyChanged}" /> 
</UserControl> 

後面的代碼:

public partial class SuperTextBox : UserControl 
{ 
    public SuperTextBox() 
    { 
     InitializeComponent(); 
    } 

    public static readonly DependencyProperty SuperValueProperty = DependencyProperty.Register(
     "SuperValue", 
     typeof(string), 
     typeof(SuperTextBox), 
     new FrameworkPropertyMetadata(string.Empty) 
    ); 

    public string SuperValue 
    { 
     get { return (string)GetValue(SuperValueProperty); } 
     set { SetValue(SuperValueProperty, value); } 
    } 
} 

好了,現在測試!

從TextBox.Text綁定到SuperTextBox.SuperValue

<TextBox x:Name="Test1" Text="{Binding ElementName=Test2, Path=SuperValue, UpdateSourceTrigger=PropertyChanged}" /> 
    <local:SuperTextBox x:Name="Test2" Grid.Row="2"/> 

測試是正確的呢! 當我在TextBox中寫東西時,SuperTextBox正在更新。 當我在SuperTextBox中寫入時,TextBox正在更新。 一切都好!

現在一個問題:
從SuperTextBox.SuperValue綁定到TextBox.Text

<TextBox x:Name="Test1"/> 
    <local:SuperTextBox x:Name="Test2" SuperValue="{Binding ElementName=Test1, Path=Text, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2"/> 

在這種情況下,當我在寫東西SuperTextBox,文本框沒有更新! enter image description here

我該如何解決這個問題?

PS:問題是非常非常長,我很抱歉,但我想準確地描述了我的問題。

回答

1

之所以一個作品和其他沒有是因爲TextBoxText依賴屬性定義綁定TwoWay默認情況下,當你的依賴項屬性SuperValue不是。如果您想要目標更新源以及源更新目標,則需要使用雙向綁定。

爲了解決這個問題,你可以添加到FrameworkPropertyMetadataOptions.BindsTwoWayByDefaultSuperValue's像這樣:

public static readonly DependencyProperty SuperValueProperty = DependencyProperty.Register(
    "SuperValue", 
    typeof(string), 
    typeof(SuperTextBox), 
    new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault) 
); 
+0

謝謝!現在一切都很清楚。 :) – Never

+0

哦,另一個案件仍然無法正常工作。你可以檢查新版本的問題 - 我添加了「Edit1」部分。 – Never

+0

對不起,但我認爲這兩個問題都非常相似,不需要創建新的「主題」。 我被刪除了「接受的答案」,因爲它可能造成「主題結束」的錯覺。 但是好的,對不起。 – Never

1

更改綁定模式爲雙向。

+0

謝謝!這是作品! 但是,爲什麼第一個和第二個案例代碼在沒有「Mode = TwoWay」的情況下工作? – Never

+0

http://msdn.microsoft.com/en-us/library/system.windows.data.binding.mode.aspx下面是一個解釋... TextBox Text「Defaults」BindingMode.TwoWay。你的財產不。 –

1

由於前兩種情況Test1知道什麼時候需要更新,但不是在第三種情況。只有Test2知道它應該在第三種情況下更新。這就是爲什麼在第三種情況下需要TwoWay模式。

編輯

  • 第一種情況是由於工作在幕後,XAML鉤 AddValueChanged事件由PropertyDescriptor曝光。有關 的原因,請參閱此鏈接here
+0

但是在第一種情況下,我可以在第二個框中寫入(它沒有關於數據綁定的任何信息),並且第一個將被更新。 – Never

+0

更新了答案。請檢查。 –

相關問題