我有一個依賴屬性的一類從裝飾器繼承,像這樣:在代碼綁定沒有反應到源對象改變
public class LoadingAdorner : Adorner
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (string), typeof (LoadingAdorner), new PropertyMetadata(default(string)));
public string Text
{
get { return (string) GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty IsShowingProperty = DependencyProperty.Register("IsShowing", typeof (bool), typeof (LoadingAdorner), new PropertyMetadata(default(bool)));
...
}
裝飾器的真的沒有任何XAML,但我想文這個裝飾者可以綁定到視圖模型。所以,我在代碼中創建綁定,在視圖的構造函數,像這樣:
private readonly LoadingAdorner _loading;
public MainWindow()
{
InitializeComponent();
_loading = new LoadingAdorner(MainPage);
var bind = new Binding("LoadingText"){Source = DataContext};
_loading.SetBinding(LoadingAdorner.TextProperty, bind);
}
DataContext的是我的視圖模型,我的視圖模型實現INotifyPropertyChanged,LoadingText是一個字符串屬性,調用OnPropertyChanged等。在所有綁定XAML工作正常,但是,代碼綁定沒有。
我認爲這是因爲在創建綁定時,視圖模型尚未設置爲DataContext(它爲null),因此在創建視圖後在行上執行此操作。如果我使用Source = this將該綁定設置爲我的視圖上的屬性,它就可以工作。
我的問題是,爲什麼XAML綁定能夠響應源對象的變化,而代碼綁定似乎不是?有沒有適當的方法讓我創建一個綁定,以便對XAML綁定類似的事情做出反應?
新的綁定(「DataContext.LoadingText」){Source = this}工作!謝謝!然而,我仍然不確定爲什麼忽略Source,並簡單地將路徑指定爲LoadingText不起作用。我有同樣的想法 - 省略源代碼,它將默認爲DataContext ... – 2012-08-08 14:16:59
@BrentYates:它會綁定到包含綁定屬性*的對象對象的'DataContext' *,在您的案例中似乎是與「MainWindow」的'DataContext'不同,所以您需要將源代碼設置爲'MainWindow'來代替它的'DataContext'。 – 2012-08-08 14:20:09