【发布时间】:2016-08-06 23:04:14
【问题描述】:
我有一段非常简单的代码来理解当我们将绑定表达式分配给任何依赖项属性然后将直接值分配给该依赖项属性时发生的行为。以下是代码
查看 XAML
<StackPanel>
<Button Click="Button_Click" Content="Assign binding value" />
<Button Click="Button_Click_1" Content="Assign direct value" />
<TextBox Text="{Binding TextSource, Mode=OneWay}" x:Name="stf" />
</StackPanel>
查看 XAML.cs
public partial class MainWindow : Window
{
MainViewViewModel vm = new MainViewViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
vm.TextSource = "Value set using binding";
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
stf.Text = "New direct value";
}
}
视图模型
public class MainViewViewModel : INotifyPropertyChanged
{
//INotifypropertychanged implementation here ...
private string _textSource;
public string TextSource
{
get { return _textSource; }
set
{
_textSource = value;
OnPropertyChanged("TextSource");
}
}
}
现在我的观察是
- 当我单击“分配绑定值”时,视图将更新为绑定源值。 (如预期的那样)
- 当我点击“分配直接值”时,视图会更新为分配给文本字段的直接值(如预期的那样)
- 我假设在这个阶段绑定被破坏,当我再次单击“分配绑定值”时它应该不起作用,意味着没有 UI 更新。它符合我的预期(如预期的那样)
- 令人困惑的一点是,当我将绑定模式设置为“TwoWay”时,第 3 点没有发生,而且无论我按什么按钮,它都始终保持工作状态。来自绑定源和直接价值。 (我不清楚 TwoWay 绑定需要对此做什么)
有人请解释一下吗?
【问题讨论】:
标签: wpf mvvm binding dependency-properties