我有一个网格,我动态地构建它,在构建的时候,我在网格中的第一个单元格(0,0)中放置一个图像。
我希望使用数据绑定,以便当用户更改位置时,图像将将其位置更改到网格中的正确位置。
用户有两个文本框,在那里他将行和列放在网格中。
任何帮助都将不胜感激。
编辑:到目前为止我所做的代码: View:我有一个包含这个用户控制器的窗口
public MyController()
{
InitializeComponent();
this.playerImage = new Image();
}
public void CreateGrid(string ansFromServer, int numberOfRows, int numberOfCols, int type)
{
this.rows = numberOfRows;
this.cols = numberOfCols;
for (int i = 0; i < this.rows; i++)
{
RowDefinition def = new RowDefinition();
mainGrid.RowDefinitions.Add(def);
}
for (int i = 0; i < this.cols; i++)
{
ColumnDefinition def = new ColumnDefinition();
mainGrid.ColumnDefinitions.Add(def);
}
}发布于 2016-04-19 11:27:08
为列和行创建一个具有两个整数属性的简单视图模型:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int gridColumn;
public int GridColumn
{
get { return gridColumn; }
set { gridColumn = value; OnPropertyChanged(); }
}
private int gridRow;
public int GridRow
{
get { return gridRow; }
set { gridRow = value; OnPropertyChanged(); }
}
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}并在XAML中使用,例如:
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<TextBox Width="50"
Text="{Binding GridColumn, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Width="50"
Text="{Binding GridRow, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Image Source="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg"
Grid.Column="{Binding GridColumn}" Grid.Row="{Binding GridRow}"/>
</Grid>
</Grid>如果您已经在后面的代码中创建了Image控件,您将设置如下的绑定:
playerImage.SetBinding(Grid.ColumnProperty, new Binding("GridColumn"));
playerImage.SetBinding(Grid.RowProperty, new Binding("GridRow"));
mainGrid.Children.Add(playerImage);https://stackoverflow.com/questions/36715783
复制相似问题