Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# UserControls的ListView绑定错误_C#_Wpf - Fatal编程技术网

C# UserControls的ListView绑定错误

C# UserControls的ListView绑定错误,c#,wpf,C#,Wpf,我试图创建一个listview,其中每个listviewitem都有一个单独的用户控件 MainPage.xaml: <ListView Name="Shortcut_Holder" ScrollViewer.VerticalScrollBarVisibility="Disabled" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionMode="Single"

我试图创建一个listview,其中每个listviewitem都有一个单独的用户控件

MainPage.xaml:

<ListView Name="Shortcut_Holder"
        ScrollViewer.VerticalScrollBarVisibility="Disabled"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled"
        SelectionMode="Single"
        SelectedIndex="-1"
        HorizontalContentAlignment="Stretch"
        ItemsSource="{Binding ShortcutList,
                            UpdateSourceTrigger=PropertyChanged,
                            ElementName=MainPage}">


    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>


    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListViewItem}">
                        <local:Exam_Folder />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListView.ItemContainerStyle>

</ListView>
                <!-- Listview ItemsSource needs to be bound to page since it's a collection of User Controls-->
                <ListView Name="Shortcut_Holder"
                          ScrollViewer.VerticalScrollBarVisibility="Disabled"
                          ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                          SelectionMode="Single"
                          SelectedIndex="-1"
                          SelectionChanged="Shortcut_Holder_SelectionChanged"
                          Background="Transparent"
                          BorderBrush="Transparent"
                          ItemsSource="{Binding ShortcutList,
                                                UpdateSourceTrigger=PropertyChanged,
                                                ElementName=MainPage}">

                    <ListView.Resources>
                        <Style TargetType="{x:Type ListViewItem}">
                            <Setter Property="Background" Value="Transparent" />
                        </Style>
                    </ListView.Resources>

                    <!-- How Listview items are laid out -->
                    <ListView.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Horizontal" />
                        </ItemsPanelTemplate>
                    </ListView.ItemsPanel>

                    <!-- Data Template for each listview item-->
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <local:Exam_Folder DisplayText="{Binding Converter={local:ExamShortcutDisplayTextValueConverter}}" />
                        </DataTemplate>
                    </ListView.ItemTemplate>

                    <!-- Style for each listview item -->
                    <ListView.ItemContainerStyle>
                        <Style TargetType="{x:Type ListViewItem}">
                            <Setter Property="Padding" Value="0" />
                            <Setter Property="Background" Value="Transparent" />
                            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                            <Setter Property="Margin" Value="5,0,5,0" />
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type ListViewItem}">
                                        <ContentPresenter />
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>

                            <!-- Change cursor style over each list item on mouse hover -->
                            <Style.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="ForceCursor" Value="True" />
                                    <Setter Property="Cursor" Value="Hand" />
                                </Trigger>
                            </Style.Triggers>

                        </Style>
                    </ListView.ItemContainerStyle>

                </ListView>
之后,应用程序崩溃。我对WPF还是相当陌生的,为此我做了最好的尝试。有什么想法吗

编辑:

我现在将listview绑定到数据,而不是用户控件。我原以为这修复了我的bug,但现在这个bug有时会出现……我想说,在我运行应用程序的时候,有50%的时间仍然会崩溃

MainPage.xaml:

<ListView Name="Shortcut_Holder"
        ScrollViewer.VerticalScrollBarVisibility="Disabled"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled"
        SelectionMode="Single"
        SelectedIndex="-1"
        HorizontalContentAlignment="Stretch"
        ItemsSource="{Binding ShortcutList,
                            UpdateSourceTrigger=PropertyChanged,
                            ElementName=MainPage}">


    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>


    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListViewItem}">
                        <local:Exam_Folder />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListView.ItemContainerStyle>

</ListView>
                <!-- Listview ItemsSource needs to be bound to page since it's a collection of User Controls-->
                <ListView Name="Shortcut_Holder"
                          ScrollViewer.VerticalScrollBarVisibility="Disabled"
                          ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                          SelectionMode="Single"
                          SelectedIndex="-1"
                          SelectionChanged="Shortcut_Holder_SelectionChanged"
                          Background="Transparent"
                          BorderBrush="Transparent"
                          ItemsSource="{Binding ShortcutList,
                                                UpdateSourceTrigger=PropertyChanged,
                                                ElementName=MainPage}">

                    <ListView.Resources>
                        <Style TargetType="{x:Type ListViewItem}">
                            <Setter Property="Background" Value="Transparent" />
                        </Style>
                    </ListView.Resources>

                    <!-- How Listview items are laid out -->
                    <ListView.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Horizontal" />
                        </ItemsPanelTemplate>
                    </ListView.ItemsPanel>

                    <!-- Data Template for each listview item-->
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <local:Exam_Folder DisplayText="{Binding Converter={local:ExamShortcutDisplayTextValueConverter}}" />
                        </DataTemplate>
                    </ListView.ItemTemplate>

                    <!-- Style for each listview item -->
                    <ListView.ItemContainerStyle>
                        <Style TargetType="{x:Type ListViewItem}">
                            <Setter Property="Padding" Value="0" />
                            <Setter Property="Background" Value="Transparent" />
                            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                            <Setter Property="Margin" Value="5,0,5,0" />
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type ListViewItem}">
                                        <ContentPresenter />
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>

                            <!-- Change cursor style over each list item on mouse hover -->
                            <Style.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="ForceCursor" Value="True" />
                                    <Setter Property="Cursor" Value="Hand" />
                                </Trigger>
                            </Style.Triggers>

                        </Style>
                    </ListView.ItemContainerStyle>

                </ListView>

MainPage.xaml.cs:

public ObservableCollection<Exam_Folder> ShortcutList
{
     get => _shortcutlist;
     set
     {
         _shortcutlist = value;
         _shortcutdataview = new CollectionViewSource();
         _shortcutdataview.Source = _shortcutlist;

         NotifyPropertyChanged("ShortcutList");
     }
}

private ObservableCollection<Exam_Folder> _shortcutlist { get; set; }

public ListCollectionView ShortCutDataView
{
    get => (ListCollectionView)_shortcutdataview.View;
}
private CollectionViewSource _shortcutdataview { get; set; }

private void HandleExamListUpdate()
{
    //Make shortcut list a new observable collection of 
    exam_folders
    ShortcutList = new ObservableCollection<Exam_Folder>(CreateExamFolderUIList());
    var view = (ListCollectionView)CollectionViewSource.GetDefaultView(ShortcutList);
    view.CustomSort = new Exam_Folder_Comparer(((MainViewModel)DataContext).CurrentExamShortcutSort);
}
private void HandleExamListUpdate(bool RefreshList = true)
    {
        //Make shortcut list a new observable collection of exam_folders
        if (ShortcutList == null || ShortcutList.Count == 0 || RefreshList)
            ShortcutList = new ObservableCollection<ExamType>(Ioc.Get<ApplicationViewModel>().CurrentPatient.PatientExams);

        var view = (ListCollectionView)CollectionViewSource.GetDefaultView(ShortcutList);
        view.CustomSort = new Exam_Folder_Comparer(((MainViewModel)DataContext).CurrentExamShortcutSort);

        //Calculate how many folders can be displayed given the width of the control
        //If there has been no change in the amount of exam folders we need to display, no need to do anything else
        //Have to do math on the overall top grid, bc the stackpanel that holds the folders would initially have its actualwidth skewed by the 
        //possible amount of controls in it.
        int holdingnumber = (int)(Math.Ceiling((Top_View.ActualWidth - TopCol1.ActualWidth - TopCol3.ActualWidth) / WIDTH_PER_SHORTCUT));

        //Apply filter based on the amount of controls we can hold
        view.Filter = new Predicate<object>(o =>
        {
            if (ShortcutList.IndexOf((ExamType)o) < holdingnumber)
                return true;

            return false;
        });
    }
private void handleexamlitupdate(bool RefreshList=true)
{
//使快捷方式列表成为新的可观察的考试文件夹集合
if(ShortcutList==null | | ShortcutList.Count==0 | | RefreshList)
ShortcutList=newobserveCollection(Ioc.Get().CurrentPatient.PatientSams);
变量视图=(ListCollectionView)CollectionViewSource.GetDefaultView(ShortcutList);
view.CustomSort=新的检查文件夹比较器(((MainViewModel)DataContext).CurrentExamShortcutSort);
//计算给定控件宽度时可以显示的文件夹数
//如果需要显示的考试文件夹数量没有变化,则无需执行任何其他操作
//必须在整个顶部网格上进行计算,bc存放文件夹的stackpanel最初的实际宽度会被
//其中可能包含的控件数量。
int holdingnumber=(int)(数学天花板((顶视图.实际宽度-TopCol1.实际宽度-TopCol3.实际宽度)/每个快捷方式的宽度));
//根据我们可以持有的控件数量应用过滤器
view.Filter=新谓词(o=>
{
if(ShortcutList.IndexOf((ExamType)o)
为了完整起见,下面是我正在使用的Usercontrol的xaml:

<UserControl x:Class="Tomo_GUI.Exam_Folder"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:Tomo_GUI"
         xmlns:svgc="http://sharpvectors.codeplex.com/svgc/"
         mc:Ignorable="d" 
         Background="Transparent"
         d:DesignHeight="100" d:DesignWidth="120">

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <svgc:SvgViewbox Grid.RowSpan="3">

        <svgc:SvgViewbox.Style>
            <Style TargetType="svgc:SvgViewbox">
                <Setter Property="local:SvgcViewboxAttachedProperties.Source" Value="{Binding ImagePath, 
                                                                                              RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver,
                                                   RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
                                 Value="True">
                        <Setter Property="local:SvgcViewboxAttachedProperties.Source" Value="\Images\TopView\Exam_File_Icon_Colored.svg" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </svgc:SvgViewbox.Style>

    </svgc:SvgViewbox>

    <TextBlock FontSize="{StaticResource FontSizeRegularSmall}"
               FontWeight="Black"
               Grid.Row="1"
               VerticalAlignment="Center"
               HorizontalAlignment="Center"
               Background="Transparent"
               Text="{Binding DisplayText,
                              RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
               Name="BlockText">
    </TextBlock>

</Grid>

现在,在最初加载集合时,或者在更改集合的筛选器时,有时会出现相同的错误。你知道会发生什么吗

public class main
{
    DataClass dc = new DataClass();
    public void yourinitialmethod()
    {
        InitializeComponents();
        this.DataContext = dc;
    }
}
不要在XAML中使用
ElementName=…
,最好使用全局(窗口)数据上下文。
它的DataContext深度会自动变化,直到项目容器本身(在本例中不需要它)

您不能将ItemSource属性绑定到一组Exam\u文件夹对象。相反,将其绑定到一组数据项,然后这些数据项将自动传递到ItemsControl的ControlTemplate(或者更好的是ItemTemplate)中的Exam_文件夹的DataContext。@Clemens非常感谢您!用户界面现在正在显示。还有一个问题…这样,我如何使用数据项来定制列表中的每个Exam_文件夹控件?我是否只绑定ControlTemplate中的任何属性?例如,其中data_成员是列表中数据项的属性,绑定到ListView的ItemsSource?是的,只需将UserControl属性绑定到数据项(即视图模型)属性。而不是将用户控件放置在ListVIEWTION控件模板中(从而破坏其鼠标的可视化和选择状态),可以考虑将其放入ListVIEW的ItMeT模板属性中的数据板中。如果不需要选择,请使用ItemsControl而不是ListView。