I have a question about WPF Databinding. I want to change the background color of a button with binding values of my ObservableCollection to the button
My Object:
public string Position1 { get; set; }
public string Position2 { get; set; }
public string Position3 { get; set; }
public string Position4 { get; set; }
public string Position5 { get; set; }
public string Position6 { get; set; }
public string Position7 { get; set; }
I wanted to have these positions inside of a ObservableCollection like below:
public ObservableCollection<Positions> Positions { get; set; }
public MainWindow()
{
InitializeComponent();
Positions = new ObservableCollection<Positions>();
Positions.Add(new Positions
{
Position1 = "Red",
Position2 = "Red",
Position3 = "Red",
Position4 = "Gray",
Position5 = "Green",
Position6 = "Green",
Position7 = "Green",
});
}
Now I am wondering how I can bind these values to the button in XAML?
I have tried this:
<Button
DataContext="Positions[0]"
Grid.Column="0"
Background="{Binding Path=Position1}"
x:Name="R1"
HorizontalAlignment="Left"
Height="100"
Margin="5,0,0,0"
VerticalAlignment="Top"
Width="109"
Click="R1_Click">
<Rectangle Stroke="Black" />
</Button>
I have tried to set the datacontext, but I am just very confused in how I can get the values inside of the list in XAML. Does anyone know how to do this?
DataContext="Positions[0]"is ok for Button, but you need DataContext for Window as well. addthis.DataContext = this;after all initializtion in constructor. - ASh