我遇到了一个我在here之前发布的问题。我仍然在努力解决这个问题,所以我尝试在一个较小的代码设置中对其进行分解。
问题是:
我将依赖项属性绑定到视图模型,它不会更新视图模型的值@construction 。
绑定似乎是正确的,因为在应用程序启动后更改XAML中的值(依赖xaml热重新加载)确实会通过更改更新视图模型。
我可以使用以下设置再现问题:
MainWindow:
<Grid>
<local:UserControl1
SomeText="My changed text"
DataContext="{Binding UserControlViewModel}"/>
</Grid>MainViewModel:
public class MainViewModel
{
public UserControlViewModel UserControlViewModel { get; set; }
public MainViewModel()
{
UserControlViewModel = new UserControlViewModel();
}
}UserControl:
<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>背后的UserControl代码:
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();
}UserControl视图模型:
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 (使用热重新加载)时,更新顺序是:
这与建筑时发生的情况正好相反。然后命令是:
F 233
这真的很奇怪。因为当属性更改回调触发时(启动期间),我可以将DependencyObject转换回UserControl并检查其数据上下文。当时的数据文本是空。
我以前的热重加载实验证明,绑定最终是完美的。
因此,
在我看来,这就像WPF中的一个bug。
发布于 2019-12-21 09:57:59
您对用例使用了错误的绑定模式。
当您指定OneWayToSource时,您只允许数据从文本框流到ViewModel中的属性,因为源是MyText属性。
尝试删除Mode=OneWayToSource,或者使用TwoWay,如果您希望从视图和ViewModel更新文本。(IIRC是TextBox控件的默认模式)。
另外,您的ViewModel是否实现了INotifyPropertyChanged接口以支持绑定?
解释不同模式的一个小摘要是在this中,所以答案
https://stackoverflow.com/questions/59435127
复制相似问题