不太确定如何解决这个问题:
我有一个“保存”按钮,上面附加了访问键......但是,如果我在文本框中输入一些内容并按访问键进行保存,则文本框不会更新我的 View 模型,因为它从未失去焦点。除了将 UpdateSourceTrigger 更改为 PropertyChanged 之外,还有什么方法可以解决这个问题?
最佳答案
您的问题是 UpdateSourceTrigger="LostFocus"
这是 TextBox 的默认设置,意味着 TextBox 只会在失去焦点时更新其绑定(bind)值
一种强制更新而不设置 UpdateSourceTrigger="PropertyChanged"
的方法是 Hook KeyPress 事件,如果组合键会触发保存,请调用 UpdateSource()
第一的
这是我喜欢在 Enter 键更新源时使用的附加属性。
它是这样使用的:
<TextBox Text="{Binding Name}"
local:TextBoxProperties.EnterUpdatesTextSource="True" />
附加属性定义如下所示:
public class TextBoxProperties
{
public static readonly DependencyProperty EnterUpdatesTextSourceProperty =
DependencyProperty.RegisterAttached("EnterUpdatesTextSource", typeof(bool), typeof(TextBoxProperties),
new PropertyMetadata(false, EnterUpdatesTextSourcePropertyChanged));
// Get
public static bool GetEnterUpdatesTextSource(DependencyObject obj)
{
return (bool)obj.GetValue(EnterUpdatesTextSourceProperty);
}
// Set
public static void SetEnterUpdatesTextSource(DependencyObject obj, bool value)
{
obj.SetValue(EnterUpdatesTextSourceProperty, value);
}
// Changed Event - Attach PreviewKeyDown handler
private static void EnterUpdatesTextSourcePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var sender = obj as UIElement;
if (obj != null)
{
if ((bool)e.NewValue)
{
sender.PreviewKeyDown += OnPreviewKeyDown_UpdateSourceIfEnter;
}
else
{
sender.PreviewKeyDown -= OnPreviewKeyDown_UpdateSourceIfEnter;
}
}
}
// If key being pressed is the Enter key, and EnterUpdatesTextSource is set to true, then update source for Text property
private static void OnPreviewKeyDown_UpdateSourceIfEnter(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
if (GetEnterUpdatesTextSource((DependencyObject)sender))
{
var obj = sender as UIElement;
BindingExpression textBinding = BindingOperations.GetBindingExpression(
obj, TextBox.TextProperty);
if (textBinding != null)
textBinding.UpdateSource();
}
}
}
}
关于c# - Prism + MVVM + Access Keys + UpdateSourceTrigger ="LostFocus"- 这不会让我在不首先失去焦点的情况下保存更新的文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8072493/