问题
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