我有以下代码:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<TextBox Text="{Binding Path=Name,
Mode=OneWayToSource,
UpdateSourceTrigger=Explicit,
FallbackValue=default text}"
KeyUp="TextBox_KeyUp"
x:Name="textBox1"/>
</Grid>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
BindingExpression exp = this.textBox1.GetBindingExpression(TextBox.TextProperty);
exp.UpdateSource();
}
}
}
public class ViewModel
{
public string Name
{
set
{
Debug.WriteLine("setting name: " + value);
}
}
}
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Window1 window = new Window1();
window.DataContext = new ViewModel();
window.Show();
}
}
我想仅在文本框中按下“Enter”键时才更新源。这很好用。但是在程序启动时绑定更新源。我怎么能避免这个?我错过了什么吗?
答案 0 :(得分:0)
问题是,DataBinding是在Show(和InitializeComponent)的调用上解析的,但这对你来说并不重要,因为那时你的DataContext还没有设置好。我不认为你可以阻止这种情况,但我有一个解决方法的想法:
在调用Show()之前不要设置DataContext。你可以这样做(例如):
public partial class Window1 : Window
{
public Window1(object dataContext)
{
InitializeComponent();
this.Loaded += (sender, e) =>
{
DataContext = dataContext;
};
}
}
和
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Window1 window = new Window1(new ViewModel());
window.Show();
}
答案 1 :(得分:-2)
将绑定模式更改为默认
<TextBox Text="{Binding Path=Name,
Mode=Default,
UpdateSourceTrigger=Explicit,
FallbackValue=default text}"
KeyUp="TextBox_KeyUp"
x:Name="textBox1"/>