【问题标题】:UWP ComboBox SelectedItem does not bind as expected in flyoutUWP ComboBox SelectedItem 在弹出窗口中未按预期绑定
【发布时间】:2018-01-18 18:13:00
【问题描述】:

我未能使用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. get PasswordTypes 源自 this.InitializeComponent()
  2. get SelectedPasswordType 源自 this.InitializeComponent()
  3. set SelectedPasswordType 源自 this.InitializeComponent()null
  4. set SelectedPasswordType 源自 this.InitializeComponent()PasswordType 的一个实例(_passwordTypes.Contains(value); 的计算结果为 true
  5. 之后不再调用这两个属性

这就是我所看到的:

我已经创建了一个分支,只需要我编写这个问题所需的最小更改:https://github.com/famoser/Bookmarked/compare/bug-failing-combobox

如果我将ComboBox 替换为ListView,则SelectedItem 设置正确。因此设置工作正常。

我是否需要为 ComboBox 设置其他属性才能使其正常工作,还是这是一个错误?

【问题讨论】:

  • 你为什么在你的绑定中使用这个:Source={StaticResource Locator}?
  • 我已经简化了代码并忘记删除它(我的ViewModels 是Locator 中的属性)。谢谢!
  • 我怀疑项目模板...如果删除 'ItemTemplate="{StaticResource PasswordTypeTemplate}"' 会起作用吗?

标签: uwp uwp-xaml


【解决方案1】:

它不起作用的原因是因为您的 ComboBox 永远不会获得焦点,因此 SelectionChanged 事件永远不会被触发。

此行为是从 Windows 10 build 14393 开始设计的。解决方法很简单 - 您只需在 AppBarButton 上手动启用 专注于交互

14393 中引入了一个名为 AllowFocusOnInteraction 的新属性,它就是这样做的。因此,如果您以 14393 及更高版本为目标,只需将其设置为 false

如果您在此之前定位任何内容,则需要在 AppBarButtonLoaded 事件中执行以下操作。

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 的出色帖子 "ComboBox on a Flyout attached to an AppBarButton loses mouse input on 1607"

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 2017-04-30
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多