c# - 不使用 XAML 进行绑定(bind) [WPF]

标签 c# wpf xaml binding

我正在设计一个内部包含 256 个按钮的应用程序,并使用 for 循环将它们添加到 C# 代码中的 WrapPanel 中。 XAML 代码中未提及这些按钮。 我的问题是,当单击其中一个时,我必须使用绑定(bind)更改其颜色。 我尝试了以下代码,但它不起作用(仅更改按钮的内容):

        private void NewButton_Click(object sender, RoutedEventArgs e)
    {
        Button btn = (Button)sender;

        for (int i = 0; i < counter; i++)
        {
            if (btn.Name == ("Butt" + i))
            {
                btn.Content = "works";
                MyData mydata = new MyData();
                Binding binding = new Binding("Color");
                binding.Source = mydata;
                binding.Source = btn;
                break;
            }
        }
    }

        private int counter = 0;
    public class MyData
    {
        public static Brush _Color = Brushes.Red;
        public Brush Color
        {
            get
            {
                return _Color;
            }
        }
    }
    public MainWindow()
    {

        InitializeComponent();

        int num = number(3);
        List<Button> btnList = new List<Button>();
        for(int i =0; i<(num*num); i++)
        {

            Button button = new Button();

            button.Name = "Butt" + counter;

            button.Content = "New";

            counter++;
            button.Height = 35;
            button.Width = 35;
            button.Click += new RoutedEventHandler(NewButton_Click);
            wp.Children.Add(button);

        }

最佳答案

如果您想要做的是将按钮的背景颜色绑定(bind)到您的“MyData”类对象,那么您就快成功了...

首先,创建绑定(bind)对象,将源设置为“mydata”的新实例,然后公开“Color”属性的路径。

然后,您需要将新的 BINDING 对象保存到按钮控件,并告诉它您希望将 BackgroundProperty 绑定(bind)到新创建的绑定(bind)。对您的代码进行以下细微调整是有效的。不完全是为什么您的方法适合您的整个项目,但希望能达到您的预期。

            if (btn.Name == ("Butt" + i))
            {
                btn.Content = "works";
                MyData mydata = new MyData();
                var oBind = new Binding
                {
                    // bind its source to this view model instance
                    Source = mydata,
                    // what property on THE BUTTON do want to be bound to.
                    Path = new PropertyPath("Color")
                };

                btn.SetBinding(BackgroundProperty, oBind);
                btn.DataContext = oBind;
                break;
            }

关于c# - 不使用 XAML 进行绑定(bind) [WPF],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37233124/

相关文章:

c# - 如何快速将数组归零?

c# - INotifyPropertyChanged 和计算属性

.net - 我应该将什么类型的对象绑定(bind)到 n 层应用程序中的 WPF 表单?

wpf - MVVM问题, View 中的事件触发

c# - Windows Phone 8.1 - 通过外部 ScrollViewer 元素处理 WebView 垂直滚动

c# - AccessText 类的 WPF 使用和预期结果

c# - EF代码第一个: Insert Many to many

c# - ASP.NET 中的两种数据绑定(bind)方式

wpf - 将用户控件与 ViewModel 类关联

c# - Akka.net/Generics and Database & Entity Framework