Binding without XAML [WPF]

假如想象 提交于 2019-12-23 02:19:17

问题


I am designing an application with 256 buttons inside, and I am adding them in the WrapPanel in C# code using for loop. These buttons are not mentioned in XAML code. My problem is that, when clicking on one of them, I have to change its color using binding. I tried following code, but it does not work (only changes the content of the button):

        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;
            }
        }
    }

and

        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);

        }

回答1:


If what you are trying to do is bind the button's background color to your "MyData" class object, you are almost there...

First, create the binding object, set the source to your new instance of "mydata", and then the path to your "Color" property exposed.

THEN, you need to save the new BINDING object to your button control and tell it you want the BackgroundProperty bound to the newly created binding. The following minor adjustment to your code works. Not exactly why your approach is what it is for your overall project, but hopefully does what you intended.

            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;
            }


来源:https://stackoverflow.com/questions/37233124/binding-without-xaml-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!