我声明了两个 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/