Windows 通用应用程序 - 禁用组合框中的项目

本文关键字:项目 禁用组合 应用程序 Windows | 更新日期: 2023-09-27 18:30:26

我正在尝试为 ComboBox 设置禁用项目,我有我的项目模型:

public class PermissionsViewItem
{
    public string Title { get; set; }
    public bool IsEnabled { get; set; }
}

ComboBox 定义了:

<ComboBox Background="WhiteSmoke" Margin="65,308,0,0" BorderThickness="0" Width="220" Padding="0" Foreground="#FF7B7A7F" ItemsSource="{Binding PermissionsViewItems}" >
        <ComboBox.ItemTemplate>
            <DataTemplate x:DataType="local:PermissionsViewItem">
                <StackPanel >
                    <Grid>
                        <Border Background="{x:Null}" BorderThickness="0" HorizontalAlignment="Left" VerticalAlignment="Center">
                            <TextBlock Text="{x:Bind Title}" FontWeight="SemiBold" />
                        </Border>
                    </Grid>
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
但是,

似乎没有办法手动设置禁用的项目,但是生成了ComboBoxItem元素(我可以在LiveVisualTree中看到它),它具有IsEnabled属性并且它可以工作。我可以通过样式访问它

<ComboBox.ItemContainerStyle>
    <Style TargetType="ComboBoxItem" >
        <Setter Property="IsEnabled" Value="False"/>
    </Style>
</ComboBox.ItemContainerStyle>

这将禁用每个项目,但不幸的是,ItemContainerStyle 没有绑定到项目,因为它具有 ComboBox 而不是 PermissionsViewItem 的上下文,所以我不能在这里使用 PermissionsViewItem.IsEnabled 属性。

有没有办法禁用特定项目(即使是黑客方式也足够了)?

Windows 通用应用程序 - 禁用组合框中的项目

您可以按如下方式覆盖组合框,并在运行时设置绑定。这对我有用

public class ZCombobox:ComboBox
    {
        protected override void PrepareContainerForItemOverride(Windows.UI.Xaml.DependencyObject element, object item)
        {
            ComboBoxItem zitem = element as ComboBoxItem;
            if (zitem != null)
            {
                Binding binding = new Binding();
                binding.Path = new PropertyPath("IsSelectable");
                zitem.SetBinding(ComboBoxItem.IsEnabledProperty, binding);
            }
            base.PrepareContainerForItemOverride(element, item);
        }
    }

Binding IsEnabled 属性 in TextBlock。

<TextBlock Text="{x:Bind Title}" FontWeight="SemiBold" IsEnabled="{Binding IsEnabled}" />