简体   繁体   English

当我尝试达到Rectangle时为空值

[英]Null values when I try to reach Rectangle

I have a uwp project that i have a booking function in and would be pleased to have some help with one thing. 我有一个uwp项目,我具有预订功能,很高兴在某件事上有帮助。

So i'm trying to reach a Rectangle in my UserControl from my Main.xaml.cs file, so i can set the Rectangles fill property. 因此,我试图从Main.xaml.cs文件中的UserControl到达Rectangle ,以便设置Rectangles填充属性。

This is how i have done it: 这就是我的做法:

Method in Main.xaml.cs for finding the child property: Main.xaml.cs用于查找子属性的方法:

private DependencyObject FindChildControl<T>(DependencyObject control, string ctrlName)
        {
            int childNumber = VisualTreeHelper.GetChildrenCount(control);
            for (int i = 0; i < childNumber; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(control, i);
                FrameworkElement fe = child as FrameworkElement;
                // Not a framework element or is null
                if (fe == null) return null;

                if (child is T && fe.Name == ctrlName)
                {
                    // Found the control so return
                    return child;
                }
                else
                {
                    // Not found it - search children
                    DependencyObject nextLevel = FindChildControl<T>(child, ctrlName);
                    if (nextLevel != null)
                        return nextLevel;
                }
            }
            return null;
        }

Inside the function where i want to call the Rectangle that is named StatusColor I do this: 在要调用名为StatusColorRectangle的函数中,我这样做:

Rectangle Rec = FindChildControl<Rectangle>(GridView1, "StatusColor") as Rectangle;

But somehow when I try to execute the code I get this error for the variable Rec : 但是以某种方式,当我尝试执行代码时,对于变量Rec收到此错误:

System.NullReferenceException: 'Object reference not set to an instance of an object.' System.NullReferenceException:'对象引用未设置为对象的实例。

I know there are many posts about this exception but i still not getting any smarter by looking at them... 我知道有很多关于此异常的帖子,但是通过查看它们,我仍然没有变得更聪明...

But as i said, I would be very pleased with someones help 但正如我所说,我会很高兴有人帮忙

Thanks in advance! 提前致谢!

EDIT: 编辑:

My xaml in Main.xaml to declare the UserControl : 我在Main.xaml xaml声明了UserControl

<GridView x:Name="GridView1" ItemContainerStyle="{StaticResource testgrid}" ItemsSource="{x:Bind Rooms}" Width="1740" Height="835" IsHitTestVisible="False" ScrollViewer.HorizontalScrollBarVisibility="Hidden" Margin="75,190,75,100" FontFamily="Segoe MDL2 Assets" IsDoubleTapEnabled="False" IsHoldingEnabled="False" IsRightTapEnabled="False" IsTapEnabled="False">
            <GridView.ItemTemplate>
                <DataTemplate x:DataType="data:Room">
                    <local:TemplateGrid x:Name="TemplateGrid"/>
                </DataTemplate>
            </GridView.ItemTemplate>
        </GridView>

And this is how my code looks like for the Rectangle : 这就是我的Rectangle代码的样子:

<Rectangle x:Name="StatusColor" x:FieldModifier="public" Margin="0,0,0,0" Height="218" VerticalAlignment="Top">
                    <Rectangle.Fill>
                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                            <GradientStop Color="#00000000" Offset="0.901"/>
                            <GradientStop Color="#CC17FF00" Offset="0"/>
                        </LinearGradientBrush>
                    </Rectangle.Fill>
                </Rectangle>

It is these lines: 这些行是:

 // Not a framework element or is null
 if (fe == null) return null;

You are exiting the loop too early. 您太早退出循环了。 When the element i is not a framework element, you should just ignore it and continue on to the next one. 当元素i不是框架元素时,您应该忽略它并继续进行下一个。

So instead of exiting when you encounter a non-framework element, just execute the next lines only when it is one: 因此,当遇到非框架元素时,不要退出,而仅在它是一个元素时才执行下一行:

 if (fe != null)
 {
    // rest of checking
 }

or alternatively: 或者:

 if (fe == null) continue;

EDIT 编辑
A slight reworking of your code to: 稍微修改一下代码即可:

    private T FindChildControl<T>(DependencyObject control, string ctrlName) 
         where T: FrameworkElement
    {
        int childNumber = VisualTreeHelper.GetChildrenCount(control);
        for (int i = 0; i < childNumber; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(control, i);
            FrameworkElement fe = child as FrameworkElement;

            // Not a framework element or is null
            if (fe == null)
            {
                continue;
            }

            if (child is T && fe.Name == ctrlName)
            {
                // Found the control so return
                return (T)child;
            }
            else
            {
                // Not found it - search children
                T nextLevel = this.FindChildControl<T>(child, ctrlName);
                if (nextLevel != null)
                {
                    return nextLevel;
                }
            }
        }

        return null;
    }

should be called with 应该与

Rectangle rec = FindChildControl<Rectangle>(GridView1, "StatusColor");

to give the correct result. 给出正确的结果。 At least it did in my test situation (with adjusted parameters). 至少在我的测试情况下(使用调整后的参数)确实如此。

The only real change was the use of continue instead of return . 唯一真正的变化是使用continue而不是return Furthermore I made use of generics to immediately return the correct type, no casting needed. 此外,我利用泛型立即返回正确的类型,无需强制转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试通过存储过程插入空值时获取SqlException - Getting a SqlException when I try to insert null values through a stored procedure 为什么在尝试保存时得到黑色矩形而不是位图 - Why I'm getting black rectangle instead my Bitmap when try to save it 当我尝试上传图像 ASP.NET 时,图像是 NULL - Image is NULL when I try to upload image ASP.NET 当我尝试反序列化时,DataContractSerializer 为所有变量返回 null - DataContractSerializer returns null for all the variables when I try to deserialize ASP.NET:当我尝试更改属性时,控件为空 - ASP.NET: Controls are null when I try to change a property 当我尝试获取GridView以显示数据时,GridView返回null - GridView returning null when I try to grab the GridView to display data 当我尝试添加图像时,MVC总是返回null - MVC always return me null when I try to add an image 当我尝试使用OLE DB读取Excel时,所有值均为空 - When I try read Excel with OLE DB all values are empty 当我尝试获取值时实体框架挂起 - Entity Framework hangs when I try to get values 创建包含其他数据库表的“ id”值的列表时,我无法达到相关表的“名称”值 - When I create a list that holds the “id” values of other database tables, I cannot reach the “name” values for the related tables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM