【问题标题】:Windows Universal App - Disable item in ComboBoxWindows 通用应用程序 - 禁用组合框中的项目
【发布时间】:2016-01-14 12:17:07
【问题描述】:

我正在尝试为 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>

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

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

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

有没有什么方法可以禁用特定的项目(即使是 hacky 方式就足够了)?

【问题讨论】:

    标签: c# xaml winrt-xaml win-universal-app


    【解决方案1】:

    在 TextBlock 中绑定 IsEnabled 属性。

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

    【讨论】:

    • 首先 - TextBlock 没有 IsEnabled 属性。第二 - 当然我可以在 DataTemplate 中模仿 IsEnabled,但是选择和突出显示仍然存在,这是由 ComboBox 控件提供的,除非我以某种方式设置 ComboBoxItem.IsEnabled = false。
    • 对不起,我检查了 wpf 项目的 IsEnabled。在 WinRT 文本块上有 Visibility 属性。试试绑定这个?
    • 再次 - 它不会帮助,它不会禁用项目。可见性属性用于显示项目,我不想隐藏或删除项目。同样禁用 TextBlock 或父网格不会删除 ComboBox 突出显示和录音效果。
    【解决方案2】:

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

    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);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多