2009-02-28 42 views
8

後,我有這樣的WPF綁定代碼:單向綁定停止工作目標手動更新

TestModel source = new TestModel(); 
TestModel target = new TestModel(); 

Bind(source, target, BindingMode.OneWay); 

source.Attribute = "1"; 
AssertAreEqual(target.Attribute, "1"); 

target.Attribute = "foo"; 

source.Attribute = "2"; 
AssertAreEqual(target.Attribute, "2"); 

第二斷言失敗!這對我來說似乎很奇怪。

另外,我嘗試了'OneWayToSource'而不是'OneWay',並且所有的按預期工作。

Bind(source, target, BindingMode.OneWayToSource); 

target.Attribute = "1"; 
AssertAreEqual(source.Attribute, "1"); 

source.Attribute = "foo"; 

target.Attribute = "2"; 
AssertAreEqual(source.Attribute, "2"); 

其他詳情:

void Bind(TestModel source, TestModel target, BindingMode mode) 
{ 
    Binding binding = new Binding(); 
    binding.Source = source; 
    binding.Path = new PropertyPath(TestModel.AttributeProperty); 
    binding.Mode = mode; 
    BindingOperations.SetBinding(target, TestModel.AttributeProperty, binding); 
} 

class TestModel : DependencyObject 
{ 
    public static readonly DependencyProperty AttributeProperty = 
     DependencyProperty.Register("Attribute", typeof(string), typeof(TestModel), new PropertyMetadata(null)); 

    public string Attribute 
    { 
     get { return (string)GetValue(AttributeProperty); } 
     set { SetValue(AttributeProperty, value); } 
    } 
} 

什麼是錯我的代碼?

回答

13

設置target.Attribute = 「foo」 的;清除綁定。

MSDN:

不僅動態資源和 綁定在同一 優先爲本地值進行操作,他們 真的是一個局部值,但與被延遲一個 值。這樣做的一個後果 是,如果你有 你設置一個動態資源或 地方屬性值綁定,任何地方 價值進行後續 替換動態綁定或 完全結合。即使您撥打 ClearValue清除本地設置的 值,動態資源或綁定 也不會被恢復。實際上,如果您在具有 動態資源或已綁定(沒有「文字」本地值)的屬性上調用ClearValue,則它們也會被清除值調用 清除。

1

不是一個綁定的專家,但我相信你正在運行到一個WPF依賴屬性的優先問題。直接設置值可能優先於綁定值。這就是爲什麼它會覆蓋綁定。

這裏有一個全面的從屬性的財產清單:http://msdn.microsoft.com/en-us/library/ms743230.aspx

+0

它使風格設置throught樣式會覆蓋模板值,並且本地值將覆蓋樣式值等,但我沒有這一點。所以不確定這是否解釋了這個問題......非常感謝。 – alex2k8 2009-02-28 20:12:24

+0

此外,這並不能解釋OneWay和OneWayToSource之間的區別 – alex2k8 2009-02-28 20:18:35

-1

如果設置綁定模式爲單向,這意味着綁定工作,只有一條出路:目標更新源變化時。

但是,目標必須是依賴項屬性,並且您擁有的代碼是CLR .NET屬性。您應該使用註冊的依賴項屬性名稱來設置目標上的值,而不僅僅是普通的.NET屬性名稱。 Jared的回答非常正確,這可能會在解決WPF依賴屬性和普通.NET CLR屬性之間的衝突時產生混淆。

如果遵循約定,依賴項屬性應該是「propertyname」+屬性的形式。

示例:TextProperty是TextBox的「Text」依賴項屬性。在代碼調用這些應該是:

TextBox1.TextProperty="value"; 

有關詳細信息有關設置結合的來源:

http://msdn.microsoft.com/en-us/library/ms743643.aspx

0

示例:TextProperty是 「文本」 文本框的 依賴項屬性。 在代碼中調用它們應該是:

TextBox1.TextProperty =「value」;

WPF屬性可以設置兩種方式:通過調用DependencyObject.SetValue方法(如:instance.SetValue(TextProperty, 「一些文本」)) 使用CLR包裝 或 (例如instance.Text =」一些文字「)。

TextBox.TextProperty是一個靜態DependencyProperty對象,因此您不能將字符串值分配給引用類型。