在我的 WPF 应用程序中,我有许多数据绑定文本框。这些UpdateSourceTrigger
绑定的LostFocus
. 使用文件菜单保存对象。我遇到的问题是可以在 TextBox 中输入一个新值,从“文件”菜单中选择“保存”,并且永远不要保留新值(在 TextBox 中可见的那个),因为访问菜单不会从 TextBox 移除焦点. 我怎样才能解决这个问题?有没有办法强制页面中的所有控件进行数据绑定?
@palehorse:好点。不幸的是,我需要使用 LostFocus 作为我的 UpdateSourceTrigger 以支持我想要的验证类型。
@dmo:我已经想到了。然而,对于一个相对简单的问题,这似乎是一个非常不雅的解决方案。此外,它要求页面上有一些控件,该控件始终可见以接收焦点。但是,我的应用程序是选项卡式的,因此没有这样的控件很容易出现。
@Nidonocu:使用菜单并没有将焦点从 TextBox 移开这一事实也让我感到困惑。然而,这就是我所看到的行为。以下简单示例演示了我的问题:
<Window x:Class="WpfApplication2.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">
<Window.Resources>
<ObjectDataProvider x:Key="MyItemProvider" />
</Window.Resources>
<DockPanel LastChildFill="True">
<Menu DockPanel.Dock="Top">
<MenuItem Header="File">
<MenuItem Header="Save" Click="MenuItem_Click" />
</MenuItem>
</Menu>
<StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}">
<Label Content="Enter some text and then File > Save:" />
<TextBox Text="{Binding ValueA}" />
<TextBox Text="{Binding ValueB}" />
</StackPanel>
</DockPanel>
</Window>
using System;
using System.Text;
using System.Windows;
using System.Windows.Data;
namespace WpfApplication2
{
public partial class Window1 : Window
{
public MyItem Item
{
get { return (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance as MyItem; }
set { (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance = value; }
}
public Window1()
{
InitializeComponent();
Item = new MyItem();
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Format("At the time of saving, the values in the TextBoxes are:\n'{0}'\nand\n'{1}'", Item.ValueA, Item.ValueB));
}
}
public class MyItem
{
public string ValueA { get; set; }
public string ValueB { get; set; }
}
}