【问题标题】:What is the code-behind equivalence of XAML <DataGrid Name="myDataGrid"/>?XAML <DataGrid Name="myDataGrid"/> 的代码隐藏等效项是什么?
【发布时间】:2022-01-26 19:35:35
【问题描述】:

我能否以编程方式添加 WPF 项目而无需手动干预 XAML?请帮我一把。

【问题讨论】:

    标签: c# wpf xaml code-behind equivalent


    【解决方案1】:

    学习 xaml 标记是 wpf 开发的必要步骤,但是是的,wpf 应用程序可以纯粹用 c# 编写:

    public class MainWindow : Window
    {
        DataGrid myDataGrid;
    
        public MainWindow()
        {
            InitializeComponent();
    
            var root = new Grid();
    
            myDataGrid = new DataGrid();
            var items = new ObservableCollection<DgItem> { new DgItem { Name = "A" } };
            myDataGrid.ItemsSource = items;
    
            root.Children.Add(myDataGrid);
            this.Content = root;
        }
    }
    
    public class DgItem
    {
        public string Name { get; set; }
    }
    

    【讨论】:

    • 好的,谢谢!我是stackoverflow的初学者。但是如何自动添加属性呢?假设你给一个名字“B”,“B”属性应该以编程方式添加到 DgItem 类中。
    • 你的意思是(myDataGrid.ItemsSource as ObservableCollection&lt;DgItem&gt;).Add(new DgItem { Name = "B" })
    • 很抱歉回复这么慢,时差太大了。可以,只要能解决问题。您的附加代码效果很好!能手!非常有帮助 !非常感谢!
    猜你喜欢
    • 2020-08-31
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    相关资源
    最近更新 更多