我相信你的錯誤是因爲你正在使用ControlTemplate,它會立即改變頁面中的數據上下文,使你的ViewModel超出範圍。更重要的是ControlTemplates不支持x:Bind。這意味着你不能使用方便的x:綁定到事件,並需要創建命令。您將不得不使用行爲來最簡單地完成此操作。
與此類似的東西。
<AutoSuggestBox>
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="TextChanged">
<core:InvokeCommandAction Command="{Binding TextChangedCommand}" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</AutoSuggestBox>
或與此類似。
public class AutoSuggestBoxAttachedProperties : Windows.UI.Xaml.DependencyObject
{
public static ICommand GetTextChangedCommand(Windows.UI.Xaml.Controls.AutoSuggestBox obj)
=> (ICommand)obj.GetValue(TextChangedCommandProperty);
public static void SetTextChangedCommand(Windows.UI.Xaml.Controls.AutoSuggestBox obj, ICommand value)
=> obj.SetValue(TextChangedCommandProperty, value);
public static readonly DependencyProperty TextChangedCommandProperty =
DependencyProperty.RegisterAttached("TextChangedCommand", typeof(ICommand),
typeof(AutoSuggestBoxAttachedProperties), new PropertyMetadata(null, TextChangedCommandChanged));
public static object GetTextChangedCommandParameter(Windows.UI.Xaml.Controls.AutoSuggestBox obj)
=> (object)obj.GetValue(TextChangedCommandParameterProperty);
public static void SetTextChangedCommandParameter(Windows.UI.Xaml.Controls.AutoSuggestBox obj, object value)
=> obj.SetValue(TextChangedCommandParameterProperty, value);
public static readonly DependencyProperty TextChangedCommandParameterProperty =
DependencyProperty.RegisterAttached("TextChangedCommandParameter", typeof(object),
typeof(AutoSuggestBoxAttachedProperties), new PropertyMetadata(null));
private static void TextChangedCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var box = d as Windows.UI.Xaml.Controls.AutoSuggestBox;
box.TextChanged -= Box_TextChanged;
if (e.NewValue != null)
{
box.TextChanged += Box_TextChanged;
}
}
private static void Box_TextChanged(Windows.UI.Xaml.Controls.AutoSuggestBox sender, Windows.UI.Xaml.Controls.AutoSuggestBoxTextChangedEventArgs args)
{
var command = GetTextChangedCommand(sender);
if (command != null)
{
var parameter = GetTextChangedCommandParameter(sender);
command.Execute(parameter);
}
}
}
然後這個。
<AutoSuggestBox
ex:AutoSuggestBoxAttachedProperties.TextChangedCommand="{Binding TextChangedCommand}" />
祝你好運。 /傑裏
也MenuFlyout將是第一,然後MenuFlyoutItem。 – mvermef