Windows 8 如何为metro控件执行绑定

Windows 8 如何为metro控件执行绑定,windows-8,windows-runtime,winrt-xaml,windows-store,Windows 8,Windows Runtime,Winrt Xaml,Windows Store,我想在用户按下保存组合键(Ctrl-S)时,将每次活动文本框的内容写回ViewModel的绑定属性 我的问题是,我无法触发绑定的执行,以便绑定文本属性反映TextBox的内容 -似乎没有GetBinding方法。因此,我无法获得绑定并手动执行。 -没有像WinForms那样执行绑定的验证方法 -将焦点从KeyDown中给予另一个控件似乎不起作用,绑定不会执行 我如何才能做到这一点?看看Aaron在其WiredParie博客文章中对此的讨论:命令实例解决方案 这里我找到了一个相对轻量级的解决方案,

我想在用户按下保存组合键(Ctrl-S)时,将每次活动文本框的内容写回ViewModel的绑定属性

我的问题是,我无法触发绑定的执行,以便绑定文本属性反映TextBox的内容

-似乎没有GetBinding方法。因此,我无法获得绑定并手动执行。
-没有像WinForms那样执行绑定的验证方法
-将焦点从KeyDown中给予另一个控件似乎不起作用,绑定不会执行


我如何才能做到这一点?

看看Aaron在其WiredParie博客文章中对此的讨论:

命令实例解决方案
这里我找到了一个相对轻量级的解决方案,但也有点“黑客”:

首先,我将焦点交给另一个控件(在我的例子中是带有绑定命令的按钮)。然后我给系统执行绑定的时间,最后我发出绑定到按钮的命令

不绑定命令的解决方案
将焦点交给另一个控件并调用Dispatcher.ProcessEvent(…)

另请参见BStateham的解决方案

这是解决问题的另一种方法

我想我现在更了解你的问题了。解决此问题的一种方法是使用子类文本框和新属性,如下所示:


然后绑定到
BindableText
属性。

我不确定这正是他所要求的。+1谢谢。它解决了我的问题。同时请参阅我找到的解决方案,它似乎工作可靠。或者你认为会有副作用吗?
btn.Focus(Windows.UI.Xaml.FocusState.Programmatic);
Dispatcher.ProcessEvent(CoreProcessEventsOption.ProcessAllIfPresent);         
btn.Command.Execute(null);
anotherControl.Focus(Windows.UI.Xaml.FocusState.Programmatic);
Dispatcher.ProcessEvent(CoreProcessEventsOption.ProcessAllIfPresent);
// Do your action here, the bound Text-property (or every other bound property) is now ready, binding has been executed
public class BindableTextBox : TextBox
{
    public string BindableText
    {
        get { return (string)GetValue(BindableTextProperty); }
        set { SetValue(BindableTextProperty, value); }
    }

    // Using a DependencyProperty as the backing store for BindableText.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty BindableTextProperty =
        DependencyProperty.Register("BindableText", typeof(string), typeof(BindableTextBox), new PropertyMetadata("", OnBindableTextChanged));

    private static void OnBindableTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs eventArgs)
    {
        ((BindableTextBox)sender).OnBindableTextChanged((string)eventArgs.OldValue, (string)eventArgs.NewValue);
    }

    public BindableTextBox()
    {
        TextChanged += BindableTextBox_TextChanged;
    }

    private void OnBindableTextChanged(string oldValue, string newValue)
    {
        Text = newValue ? ? string.Empty; // null is not allowed as value!
    }

    private void BindableTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        BindableText = Text;
    }    
}