2016-11-24 1 views
1

Я использую шаблон MVVM для привязки свойств AutoSuggestBox в ViewPage к моей ViewModel. Это прекрасно работает, когда я нахожусь внутри Grid или stackPanel.Шаблон 10 UWP Как связать с autoSuggestBox внутри MenuFlyoutItem

Но как только я поместил AutoSuggestBox внутри MenuFlyout кнопки. Я получаю следующую ошибку во время компиляции

Ошибка Ссылка на объект не установлена ​​в экземпляр объекта.

Любые указания по связыванию свойств AutoSuggestBox внутри MenuFlyoutItem ??

Вот код, который я пытаюсь скомпилировать.

<Button> 
    <Button.Flyout> 
    <MenuFlyoutItem > 
      <MenuFlyoutItem.Template> 
      <ControlTemplate TargetType="MenuFlyoutItem"> 
       <AutoSuggestBox Header="What's your name?" 
        TextChanged="{x:Bind ViewModel.FilterUsuals}" 
        QuerySubmitted="{x:Bind ViewModel.ProcessQuery}" 
        SuggestionChosen="{x:Bind ViewModel.ProcessChoice}" 
        ItemsSource="{Binding Elements}" 
        Text="{x:Bind ViewModel.SearchText, Mode=TwoWay}" 
        QueryIcon="Find" /> 
      </ControlTemplate> 
      </MenuFlyoutItem.Template> 
    </MenuFlyoutItem> 
</Button.Flyout> 
</Button > 
+0

Также MenuFlyout будет первым, а затем MenuFlyoutItem. – mvermef

ответ

0

Я считаю, что ваша ошибка связана с тем, что вы используете ControlTemplate, который немедленно меняет контекст данных со страницы, что делает вашу ViewModel недоступной. Более важно то, что x: Bind не поддерживается в ControlTemplates. Это означает, что вы не можете использовать удобный 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}" /> 

Удачи./Jerry

1
<Button Content="Button" Margin="10,0" > 
    <Button.Flyout> 
     <Flyout Placement="Top"> 
       <AutoSuggestBox ... /> 
     </Flyout> 
    </Button.Flyout> 
    </Button> 

Не уверен, как к характеру необходимости, чтобы быть в MenuFlyout. Зачем причинять себе столько боли, делая это так, когда это может быть просто в подтипе Flyout внутри самой кнопки?

Что касается привязки, это не имеет никакого отношения к Template10. Вероятно, это связано с коллекцией, которая не была инициализирована. Убедитесь, что созданные вами коллекции были созданы правильно (например, new List<yourtype>())

Смежные вопросы