WPF前台xaml中的控件名在后台拿不到,后台代码中显示“当前上下文不存在名称‘xxx’”

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF前台xaml中的控件名在后台拿不到,后台代码中显示“当前上下文不存在名称‘xxx’”相关的知识,希望对你有一定的参考价值。

在前台页面有个文本框控件,<TextBox x:Name="txtFolder" Width="115" MaxLength="256"/>,后台代码txtFolder显示当前上下文不存在名称“txtFolder”

如果这个textbox是一个页面上的控件,应该是可以在后台直接获得的。你可以重新编译下工程项目就行了。如果这个textbox是在某个控件的template里的话,后台是不能直接获取的,但你可以通过视觉树的方式获取,网上有相关资料可以查阅借鉴。 参考技术A Name改成:
<TextBox Name="txtFolder" Width="115" MaxLength="256"/>
参考技术B TextBox textBox1 = new TextBox();
textBox1.Text = "";
foreach (var item in XML.lists)

textBox1.Text = textBox1.Text + item + "\r\n";//用了MVVM模式之后,不能直接用前台的控件name属性

C# WPF从后台代码生成行列可变的表格

z概述

      WPF常用的表格控件是DataGrid,这个控件在前台XAML编写的话,一般列已经固定,然后给每个列去绑定数据,但是如果我的列不固定,随着运算结果变动呢?这时候DataGrid,就比较难实现这个需求,这节我就从后台代码去添加控件去实现这个功能.

效果演示

实现方法

-. 前台XAML:

<dxlc:LayoutControl>


                    <Grid HorizontalAlignment="Left" VerticalAlignment="Top" 
                        cal:Message.Attach="[Event Loaded]=[Grid_Loaded($source,$eventArgs)]" />


                </dxlc:LayoutControl>

这里我把grid放到了dxlc:LayoutControl中,这样可以实现grid尺寸超出界面分配的长宽时,横纵出现滑动条:如下图

-.后台代码:

数据模型:

public class WidthMetrologyDTO
    
        /// <summary>
        /// 
        /// </summary>
        public bool IsMeasureSuccess  get; set; 


        /// <summary>
        /// 
        /// </summary>
        public double Degree  get; set; 


        /// <summary>
        /// 
        /// </summary>
        public string ImageFilePath  get; set; 


        /// <summary>
        /// 
        /// </summary>
        public double Width  get; set; 


        public double EdgeNum  get; set; 


        public List<EdgePosition> EdgePositions  get; set; 
    


    public class EdgePosition
    
        public double EdgesAmplitude  get; set; 
    

①定义grid以及数据集合:

public Grid resultDisplayGrid;
   public BindableCollection<WidthMetrologyDTO> WidthMetrologyData  get; set; 
            = new BindableCollection<WidthMetrologyDTO>();

②控件加载时获取grid对象:

public void Grid_Loaded(object sender, RoutedEventArgs e)
        
            resultDisplayGrid = (Grid)sender;
        

③添加数据集合:

public void ResultDispaly()
        
            try
            
                WidthMetrologyData.Clear();
                WidthMetrologyData.Add(new WidthMetrologyDTO
                
                    Width = 345.1,
                    EdgeNum = 3,
                    EdgePositions = new List<EdgePosition>
                    
                        new EdgePosition()EdgesAmplitude = 1.1,
                        new EdgePosition()EdgesAmplitude = 2.2,
                        new EdgePosition()EdgesAmplitude = 3.3,
                    ,
                );
                WidthMetrologyData.Add(new WidthMetrologyDTO
                
                    Width = 345.2,
                    EdgeNum = 2,
                    EdgePositions = new List<EdgePosition>
                    
                        new EdgePosition()EdgesAmplitude = 4.4,
                        new EdgePosition()EdgesAmplitude = 5.5,
                    ,
                );
                WidthMetrologyData.Add(new WidthMetrologyDTO
                
                    Width = 345.3,
                    EdgeNum = 4,
                    EdgePositions = new List<EdgePosition>
                    
                        new EdgePosition()EdgesAmplitude = 6.6,
                        new EdgePosition()EdgesAmplitude = 7.7,
                        new EdgePosition()EdgesAmplitude = 8.8,
                         new EdgePosition()EdgesAmplitude = 9.9,
                    ,
                );
                WidthMetrologyData.Add(new WidthMetrologyDTO
                
                    Width = 345.0,
                    EdgeNum = 1,
                    EdgePositions = new List<EdgePosition>
                    
                        new EdgePosition()EdgesAmplitude = 0.66,
                    ,
                );
                AddResultGrid();
            
            catch (Exception ex)
            
                //logger.Debug($"ResultData add fail : ex");
            
        

④数据表格生成

public void AddResultGrid()
        
            try
            
                resultDisplayGrid.Children.Clear();
                var gridColumns = 2 + WidthMetrologyData.OrderByDescending(index => index.EdgePositions.Count).FirstOrDefault().EdgePositions.Count;
                var gridRows = 16;


                //添加grid行
                for (int i = 0; i < gridColumns; i++)
                
                    var columnDefinition = new ColumnDefinition();
                    resultDisplayGrid.ColumnDefinitions.Add(columnDefinition);
                    if (i == 1)
                    
                        columnDefinition.Width = new GridLength(2, GridUnitType.Star);//相对尺寸
                    
                    else
                    
                        columnDefinition.Width = new GridLength(1, GridUnitType.Star);
                    
                    //columnDefinition.Width = GridLength.Auto;
                
                //添加grid列
                for (int i = 0; i < gridRows; i++)
                
                    var rowDefinition = new RowDefinition();
                    resultDisplayGrid.RowDefinitions.Add(rowDefinition);
                    rowDefinition.Height = new GridLength(30, GridUnitType.Pixel);//绝对尺寸
                


                //添加数据
                //var controlWidth = 100;
                //var controlHeight = 30;
                for (int degreeIndex = 0; degreeIndex < WidthMetrologyData.Count; degreeIndex++)
                
                    var rowsCount = 3;
                    var columnsCount = WidthMetrologyData[degreeIndex].EdgePositions.Count;
  
                    for (int row = 0; row < rowsCount; row++)
                        for (int column = 0; column < columnsCount + 2; column++)
                        
                            TextBlock tb = new TextBlock();
                            //tb.Width = controlWidth;
                            //tb.Height = controlHeight;
                            //tb.HorizontalAlignment = HorizontalAlignment.Left;
                            //tb.VerticalAlignment = VerticalAlignment.Center;




                            Border border = new Border();
                            border.BorderBrush = System.Windows.Media.Brushes.BlueViolet;
                            border.BorderThickness = new Thickness(1);


                            border.Child = tb;
                            border.SetValue(Grid.RowProperty, row + degreeIndex * 4);
                            border.SetValue(Grid.ColumnProperty, column);
                            resultDisplayGrid.Children.Add(border);


                            if (row == 0 && column >= 2)
                            
                                tb.Text = (column - 1).ToString();
                            
                            else if (row == 1 && column >= 2)
                            
                                tb.Text = WidthMetrologyData[degreeIndex].EdgePositions[column - 2].EdgesAmplitude.ToString();
                            
                            else if (row == 2 && column >= 2)
                            
                                if (column == 2)
                                
                                    tb.Text = WidthMetrologyData[degreeIndex].Width.ToString();
                                    //tb.Width = columnsCount * controlWidth;
                                    tb.SetValue(Grid.ColumnSpanProperty, columnsCount);
                                
                                else
                                
                                    continue;
                                
                            


                            if (column == 0)
                            
                                if (row == 0)
                                
                                    switch (degreeIndex)
                                    
                                        case 0:
                                            tb.Text = "第一组"; break;
                                        case 1:
                                            tb.Text = "第二组"; break;
                                        case 2:
                                            tb.Text = "第三组"; break;
                                        case 3:
                                            tb.Text = "第四组"; break;
                                        default: break;
                                    
                                    //tb.Height = 3 * controlHeight;
                                    tb.SetValue(Grid.RowSpanProperty, 3);
                                
                                else
                                
                                    continue;
                                
                            


                            if (column == 1)
                            
                                switch (row)
                                
                                    case 0:
                                        tb.Text = "ID"; break;
                                    case 1:
                                        tb.Text = "Value"; break;
                                    case 2:
                                        tb.Text = "Fraction"; break;
                                    default:
                                        tb.Text = string.Empty; break;
                                
                                //tb.Width = controlWidth;
                            


                        
                


                resultDisplayGrid.Width = (gridColumns + 1)* 40;
                //resultDisplayGrid.Height = gridRows * controlHeight;
            
            catch (Exception ex)
            
                //logger.Error($"Add result  grid fail,ex");
            
        

解释:

-. grid添加行以及尺寸设置:ridUnitType.Pixel代表绝对尺寸,GridUnitType.Star相对尺寸

var rowDefinition = new RowDefinition();
                    resultDisplayGrid.RowDefinitions.Add(rowDefinition);
                    rowDefinition.Height = new GridLength(30, GridUnitType.Pixel);//绝对尺寸

自动尺寸:

columnDefinition.Width = GridLength.Auto;

-. link的使用:按照集合中EdgePositions数量降序排列后获取第一个列表值

WidthMetrologyData.OrderByDescending(index => index.EdgePositions.Count).FirstOrDefault().EdgePositions.Count;

-.生成控件并添加到grid中,并通过SetValue设置控件在grid中的行列位置

TextBlock tb = new TextBlock();
                            //tb.Width = controlWidth;
                            //tb.Height = controlHeight;
                            //tb.HorizontalAlignment = HorizontalAlignment.Left;
                            //tb.VerticalAlignment = VerticalAlignment.Center;




                            Border border = new Border();
                            border.BorderBrush = System.Windows.Media.Brushes.BlueViolet;
                            border.BorderThickness = new Thickness(1);


                            border.Child = tb;
                            border.SetValue(Grid.RowProperty, row + degreeIndex * 4);
                            border.SetValue(Grid.ColumnProperty, column);
                            resultDisplayGrid.Children.Add(border);

源码

链接:https://pan.baidu.com/s/1mgzyTRVwvq1XpJ6y0iyVww 

提取码:6666

技术群:添加小编微信并备注进群

小编微信:mm1552923   

公众号:dotNet编程大全    

以上是关于WPF前台xaml中的控件名在后台拿不到,后台代码中显示“当前上下文不存在名称‘xxx’”的主要内容,如果未能解决你的问题,请参考以下文章

C# WPF从后台代码生成行列可变的表格

WPF应用程序中,调用用户控件时,可以访问到在这个用户控件Xaml代码中的所有内容,这样岂不是不安全?

C# WPF后台动态添加控件(经典)

WPF后台如何获得前台XAML中对象

C# WPF后台动态添加控件(经典)

XAML与C#与WPF三者到底有啥关系?