c# - WPF 将 slider 和文本框值绑定(bind)到静态 int 值

标签 c# wpf

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

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

我需要将它们绑定(bind)到我的 slider 和文本框,我该怎么做?

<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}"/>

我只在 slider 中绑定(bind) CELLS_X,因为我现在不关心 Y 是什么。

编辑

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

它们在 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
}

最佳答案

首先,您不能绑定(bind)到字段,因此您需要将字段转换为属性。但是,即使您这样做,您也不会收到静态属性的更改通知。解决这个问题的一种方法是创建并提出一个 <i>PropertyName</i>Changed静态事件。对于少数几个属性来说,这将变得站不住脚。

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}"/>

关于c# - WPF 将 slider 和文本框值绑定(bind)到静态 int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25125544/

相关文章:

c# - 在C#.Net中自动调用函数

c# - FFT数字音频

c# - 如何实现异步 File.Delete/Create/Move?

WPF:将标志与复选框绑定(bind)

c# - 抑制 GridViewColumn 上的鼠标悬停效果

c# - 当线程使用调度程序并且主线程正在等待线程完成时出现死锁

c# - LINQ 中的 Where IN 子句

wpf - 为什么我的 Popup 在某些机器上显示在 Placement 属性的对面?

wpf - 如何将 WPF 窗口移动到屏幕顶部上方?

c# - 141 是可以同时设置动画的 WPF 面板项的最大数量吗?