UWP ComboBox在Flyout中的SelectedItem绑定不如预期

5

我无法使用ComboboxSelectedItem属性。已正确绑定和显示一个项目,但无法更改为另一个项目。如果尝试选择另一个项目,则项目列表将正确关闭,但是不会调用SelectedItem(也不是setter或getter),并且所选项目不会更改。

我的XAML如下:

<ComboBox
    ItemsSource="{Binding PasswordTypes}"
    ItemTemplate="{StaticResource PasswordTypeTemplate}"
    SelectedItem="{Binding SelectedPasswordType, Mode=TwoWay}"
    />

相关的ViewModel代码:

public MyViewModel()
{
    //these are the only two assignments in code of those two properties
    _passwordTypes = new ObservableCollection<PasswordType>(nonEmptyList);
    _selectedPasswordType = PasswordTypes.First();
}

private PasswordType _selectedPasswordType;
public PasswordType SelectedPasswordType
{
    get => _selectedPasswordType;
    set => Set(ref _selectedPasswordType, value);
}

private ObservableCollection<PasswordType> _passwordTypes;
public ObservableCollection<PasswordType> PasswordTypes
{
    get => _passwordTypes;
    set => Set(ref _passwordTypes, value);
}

以下是两个属性的调用:
  1. 源自this.InitializeComponent()get PasswordTypes
  2. 源自this.InitializeComponent()get SelectedPasswordType
  3. 将源自this.InitializeComponent()set SelectedPasswordType设置为null
  4. 将源自this.InitializeComponent()set SelectedPasswordType设置为PasswordType实例,(_passwordTypes.Contains(value);评估为true)
  5. 之后不会再调用这两个属性
下面是我看到的: ComboBox behaviour 我创建了一个分支,加入了必要的最小更改才能提出这个问题: https://github.com/famoser/Bookmarked/compare/bug-failing-combobox 如果我用ListView替换ComboBox,那么SelectedItem就会被正确地设置。因此,安装正确。
我需要为ComboBox设置其他属性才能使其工作,还是这是一个错误?

为什么在你的绑定中使用:Source={StaticResource Locator}? - Isma
我简化了代码,忘记删除这个(我的ViewModel是Locator中的属性)。谢谢! - Florian Moser
我的怀疑落在项目模板上...如果你移除 'ItemTemplate="{StaticResource PasswordTypeTemplate}"',这个会起作用吗? - David Oliver
1个回答

9
原因是因为您的ComboBox从未获得焦点,因此SelectionChanged事件从未触发。这种行为是自Windows 10版本14393以来的设计。解决方法很简单 - 您只需要在AppBarButton上手动启用交互焦点即可。 Windows 10版本14393引入了一个名为AllowFocusOnInteraction的新属性,它可以实现这一点。因此,如果您的目标是14393及更高版本,则只需将其设置为false。如果您的目标版本低于该版本,则需要在AppBarButton的Loaded事件中执行以下操作。
private void AppBarButton_Loaded(object sender, RoutedEventArgs e)
{
    var allowFocusOnInteractionAvailable =
        Windows.Foundation.Metadata.ApiInformation.IsPropertyPresent(
            "Windows.UI.Xaml.FrameworkElement",
            "AllowFocusOnInteraction");

    if (allowFocusOnInteractionAvailable)
    {
        if (sender is FrameworkElement s)
        {
            s.AllowFocusOnInteraction = true;
        }
    }
}

要了解更多关于这种行为的内容,请参考Rob Caplan的出色文章“附加在AppBarButton上的Flyout中的ComboBox在1607上失去鼠标输入”


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接