【问题标题】:How to make some ListView items 'greyed-out' and unselectable?如何使某些 ListView 项目“变灰”且无法选择?
【发布时间】:2016-04-09 02:40:40
【问题描述】:

ListView 控件中的某些项目是可选择的并且具有普通文本。 然而,一些项目虽然作为项目包含在 ListView 中,但将无法选择/无法点击并且“灰显”。

在 Windows-Store-Apps 中,我们可以在 ListView 中选择 Single/Multiple/None 项。但是,主要在代码中如何使某些索引处的某些项目不可选择/不可点击和“灰显”?

我设法在某个索引处访问了 ListView 的 Item:

myListView.ItemContainerGenerator.ContainerFromIndex(i)

但我找不到任何自定义其选定事件处理程序的选项。 知道如何实现吗?

【问题讨论】:

  • 你是在单选模式还是多选模式下尝试这个?
  • 单选模式
  • 查看我的回答可能会解决您的问题。

标签: c# windows-store-apps winrt-xaml windows-8.1-universal


【解决方案1】:

在单选模式下。 首先将一个布尔属性添加到绑定类型的类中,它定义了哪些项目可以像这样点击

  class TestClass
  {
    Boolean IsClickAllowed{get;set;}
    string name{get;set;}
  }

然后创建一个TestClass类型的源列表,并像这样将其设置为Listview的itemssource

var TempList=new List<>()
                    {
                        new TextClass(){IsClickAllowed=false,name="First Item"},
                        new TextClass(){IsClickAllowed=true,name="Second Item"},
                        new TextClass(){IsClickAllowed=false,name="Third Item"},
                    };
                    MyList.ItemsSource=TempList;

以及为实现 DataTemplateSelector 的非可点击项设置不同的 DataTemplate 以及最后在 ItemClick 事件中的点击句柄灰显。您需要将 IsItemClickEnabled 设置为 true。

private void MyList_ItemClick(object sender, ItemClickEventArgs e)
        {
            var item = e.ClickedItem as TestClass;
            if (item != null){
if(item.IsClickAllowed){
//Do Stuff here
}else
{
//Do Nothing
}
        }}

希望对你有帮助。

【讨论】:

  • 感谢您的回答@Rohit!我使用isEnabled 找到了一个最佳选择
【解决方案2】:

我找到了解决办法:

我已经覆盖了ListView 控件并创建了一个 StripedListView。然后通过覆盖PrepareContainerForItemOverride,它负责在创建后设置ListViewItem控件,您可以修改背景颜色并将ItemListView.isEnabled选项设置为false:

public class StripedListView : ListView
    {          
        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);
            var listViewItem = element as ListViewItem;
            if (listViewItem != null)
            {
                var index = IndexFromContainer(element);

                if (Words.arrayW[index].Length > 0)
                {
                    listViewItem.Foreground = new SolidColorBrush(Colors.Black);

                }
                else
                {
                    listViewItem.Foreground = new SolidColorBrush(Colors.Gray); 
                    listViewItem.IsEnabled = false;
                }
            }
        }
    }

在 Xaml 中:

<controls:StripedListView x:Name="letterListView" ItemsSource="{Binding}">   
      <controls:StripedListView.ItemTemplate>  
         <DataTemplate>                           
                etc...              
         </DataTemplate>
      </controls:StripedListView.ItemTemplate>
</controls:StripedListView>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多