将滑块和文本框的值绑定为静态整型值

本文关键字:绑定 静态 整型 文本 | 更新日期: 2023-09-27 18:16:15

我声明了两个public static int变量(它们是常量,但需要更改,所以我将它们设置为静态):

    public static int CELLS_X = 381;
    public static int CELLS_Y = 185;

我需要将它们绑定到滑块和文本框,我该怎么做呢?

<TextBox Width="70" 
         Text="{Binding ElementName=cellSizesSlider, Path=Value, Mode=TwoWay}" 
         Margin="5" />
<Slider x:Name="cellSizesSlider" 
        Width="100" 
        Margin="5" 
        Minimum="0"
        Maximum="400" 
        TickPlacement="BottomRight" 
        TickFrequency="10" 
        IsSnapToTickEnabled="True" 
        Value="{Binding Path=CELLS_X, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

我只在滑块中绑定CELLS_X因为我现在不关心Y是多少

编辑

它们是静态的,因为我在代码的不同地方使用它们来声明Conway's Game of Life棋盘的初始网格大小。它们是我用于初始启动时的网格大小的常量,但我希望它是动态的。

它们被声明在MainWindow类的顶部:

public partial class MainWindow : Window {
    public const double CELL_SIZE = 5;
    public static int CELLS_X = 381;
    public static int CELLS_Y = 185;
    private BoardModel model = new BoardModel();
    public MainWindow() {
        InitializeComponent();
        this.model.Update += new BoardModel.OnUpdate(model_Update);
        ConwaysLifeBoard.Width = (MainWindow.CELL_SIZE * MainWindow.CELLS_X) + 40;
        ConwaysLifeBoard.Height = (MainWindow.CELL_SIZE * MainWindow.CELLS_Y) + 100;
    }
    // Details elided
}

将滑块和文本框的值绑定为静态整型值

首先,您不能绑定到字段,因此您需要将字段转换为属性。但是,即使这样做了,也不会收到静态属性的更改通知。解决这个问题的一种方法是创建并引发一个PropertyNameChanged静态事件。对于少数属性来说,这将是站不住脚的。

private static int _cellsX = 381;
// Static property to bind to
public static int CellsX {
     get{return _cellsX;} 
     set{
        _cellsX = value;
        RaiseCellsXChanged();
    }
}
// Static event to create change notification
public static event EventHandler CellsXChanged;
// Event invocator
private static void RaiseCellsXChanged() {
    EventHandler handler = CellsXChanged;
    if (handler != null) {
        handler(null, EventArgs.Empty);
    }
}

和XAML

<Slider x:Name="cellSizesSlider" 
    Width="100" 
    Margin="5" 
    Minimum="0"
    Maximum="400" 
    TickPlacement="BottomRight" 
    TickFrequency="10" 
    IsSnapToTickEnabled="True" 
    Value="{Binding Path=CellsX}"/>