簡體   English   中英

自定義依賴項屬性綁定

[英]Custom Dependency Property bindings

我正在嘗試實現從TextBox繼承的numberBox類

 public class numberBox : TextBox

我聲明了一個自定義的DependencyProperty numberProperty

 public static readonly DependencyProperty numberProperty = DependencyProperty.Register("number", typeof(object), typeof(numberBox), new PropertyMetadata(0));
    public object number
    {
        get { return GetValue(numberProperty); }
        set { SetValue(numberProperty, value); }
    }

在numberBox的構造函數中,我有一個綁定來同步文本和數字

 public numberBox()
    {
        Binding b = new Binding("number");            
        b.Source = this;
        this.SetBinding(TextProperty, b);
    }

在一種情況下,我以這種方式使用numberBox

 <BC:numberBox x:Name="numC1" number={Binding ElementName=dg, Path=SelectedItem.C1} />

“ dg”是一個DataGrid,我的目標是當DataGrid選擇更改時,numberBox顯示所選項目的值

PS我知道我可以使用DataGrid.SelectionChanged事件來實現相同的行為,但我只想了解有關綁定的更多信息

到目前為止,一切工作正常,當我選擇DataGrid的不同行時,numberBox顯示正確的值,但是,當numberBox獲得焦點時,對其進行編輯,失去焦點后,numberProperty綁定就消失了,這意味着當DataGrid選擇的項目更改時,它不再將值帶入numberBox

我設置一個斷點並在numberBox中檢查“ this.GetBindingExpression(numberProperty)”,在編輯此numberBox並失去焦點后,它返回null

有誰知道原因,我應該如何解決?

非常感謝。

您可以通過設置

b.Mode = BindingMode.OneWay;

在numberBox的構造函數中。 通過將TextProperty綁定回源“數字”,可以清除numberProperty和網格之間的綁定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM