数据绑定网格位置 - wpf

时间:2016-04-19 10:32:09

标签: c# wpf grid

我有一个网格,我是动态构建的,在构建时我将图像放在网格的第一个单元格(0,0)中。

我想使用数据绑定,这样当用户更改位置时,图像会将其位置更改为网格中的正确位置。

用户有两个texbox,他把行和列放在网格中。

任何帮助将不胜感激。

编辑: 我到目前为止所做的代码: 视图:     我有一个包含此用户控制器的窗口

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

1 个答案:

答案 0 :(得分:0)

创建一个简单的视图模型,其中包含列和行的两个整数属性:

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