繁体   English   中英

数据绑定网格位置-WPF

[英]Databinding Grid position - wpf

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

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

用户有2个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);
        }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM