I’m not sure if the array is really the issue here but I have a rectangle which I want to move from one side of the window to the other when the MouseUp event is raised. I have this rectangle bound to an array element and the MouseUp event handler method changes the value of that array. I know the handler method works as it can pull up a message box fine, just not switch the position of the rectangle.
Note: The array is necessary, this is just code for testing these concepts, not my actual project.
Also the simplest method to solve this issue would be greatly appreciated.
C# Code:
namespace WPFTestingApplication
{
public static class GridProperties
{
public static int[] gridColumn = { 0 };
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Rect_MouseUp_1(object sender, MouseButtonEventArgs e)
{
GridProperties.gridColumn[0] = 1;
}
}
}
XAML Code:
<Window x:Class="WPFTestingApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFTestingApplication"
Title="MainWindow" Height="200" Width="400">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Rectangle Name="Rect" Grid.Column="{Binding [0], Source={x:Static local:GridProperties.gridColumn}, Mode=OneWay}" Fill="DarkGray" Margin="5" MouseUp="Rect_MouseUp_1"/>
</Grid>
</Window>
The array is the problem. You should read up on INotifyPropertyChanged, nothing you bind to will be updated without it.
If you can, change your array to an
ObservableCollectionwhich implementsINotifyPropertyChangedfor changes to its elements. You can index it just like it’s an array.You may also have issues with storing the property collection in a static class. Static classes and properties don’t have property changed notifications. If it’s possible for the GridProperties to be a property on the window class that will be easier. Then, set the DataContext of the window to itself.
Something like this works for your example. Can’t tell if you have something more complicated in your actual project though.
C#:
xaml: