[英]WPF Dependency property changed but not effectuated in binding
我遇到了我之前在這里發布的問題。 我仍在努力解決這個問題,所以我試圖在一個較小的代碼設置中分解它。
問題:
我有一個依賴屬性綁定到視圖模型,它不會用它的更改值@construction time更新視圖模型。
綁定似乎是正確的,因為在應用程序啟動后更改 XAML 中的值(依賴於 xaml 熱重載)確實會使用更改更新視圖模型。
我可以通過以下設置重現該問題:
主窗口:
<Grid>
<local:UserControl1
SomeText="My changed text"
DataContext="{Binding UserControlViewModel}"/>
</Grid>
主視圖模型:
public class MainViewModel
{
public UserControlViewModel UserControlViewModel { get; set; }
public MainViewModel()
{
UserControlViewModel = new UserControlViewModel();
}
}
用戶控件:
<UserControl.Resources>
<Style TargetType="local:UserControl1">
<Setter Property="SomeText" Value="{Binding MyText, Mode=OneWayToSource}"></Setter>
</Style>
</UserControl.Resources>
<Grid>
<TextBlock Text="{Binding MyText}"></TextBlock>
</Grid>
背后的用戶控制代碼:
public static readonly DependencyProperty SomeTextProperty = DependencyProperty.Register(
nameof(SomeText),
typeof(string),
typeof(UserControl1),
new PropertyMetadata("default text", PropertyChangedCallback));
public string SomeText { get; set; }
private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// first and only update: 'default text' => 'My changed text'
}
public UserControl1()
{
InitializeComponent();
}
用戶控件視圖模型:
public class UserControlViewModel
{
// Setter is called with 'default text'
// AFTER the property changed callback is triggered with updated text
public string MyText { get; set; }
}
當我運行應用程序時,會顯示文本“默認文本”,而我預計會顯示“我更改的文本”。
當我在 XAML 中更改 SomeText 屬性時,我再次看到更改的回調觸發,因此我看到視圖模型設置器得到更新。 這次改變的值。 因此,綁定似乎工作正常,但在啟動期間它無法使用(已知的)更改值更新視圖模型。
任何人都可以解釋是什么導致了這個問題? 有沒有辦法解決這個問題?
我剛剛發現,當我更改 XAML (使用熱重載)時,更新順序是:
這與構建時發生的情況相反。 那么順序是:
這真的很奇怪。 因為當 Property Changed 回調觸發時(在啟動期間),我可以將DependencyObject
回我的 UserControl 並檢查其數據上下文。 數據上下文當時為空。
我之前的熱重載實驗證明最終綁定工作完美。
對我來說,這看起來像是 WPF 中的一個錯誤。
您為您的用例使用了錯誤的綁定模式。
當您指定 OneWayToSource 時,您只允許數據從您的文本框流向您的 ViewModel 中的屬性,因為源是 MyText 屬性。
嘗試刪除 Mode=OneWayToSource,或者如果您希望從 View 和 ViewModel 更新文本,請使用 TwoWay。 (IIRC TwoWay 是 TextBox 控件的默認模式)。
此外,您的 ViewModel 是否實現了 INotifyPropertyChanged 接口以支持綁定?
一個解釋不同模式的小總結在這個SO 答案中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.