我正在编写一个WPF应用程序,我有一个文本框供用户输入视频播放的每秒帧数。这个文本框的值被绑定到后台代码中的依赖属性(试图像一个好的设计器一样遵循MVVM )。我的问题是,当外部更改FPS值时,文本框不会自动更新。例如,用户可以使用滑块控制值。依赖关系属性值由滑块正确更改,但文本框文本永远不会更新,当然,除非我手动使用GetBindingExpression(..).UpdateTarget() (这是我在等待更好的解决方案之前实现的方法)。有没有人知道这是预期的功能,还是我设置错了?
谢谢,麦克斯
XAML的TextBox标签:
<TextBox Text="{Binding FPS}" Name="tbFPS" FlowDirection="RightToLeft"/>依赖属性的代码隐藏:
#region public dependency property int FPS
public static readonly DependencyProperty FPSProperty =
DependencyProperty.Register("FPSProperty", typeof(int), typeof(GlobalSettings),
new PropertyMetadata(MainWindow.appState.gSettings.fps,FPSChanged,FPSCoerce),
FPSValidate);
public int FPS
{
get { return (int)GetValue(FPSProperty); }
set { SetValue(FPSProperty, value); }
}
private static bool FPSValidate(object value)
{
return true;
}
private static object FPSCoerce(DependencyObject obj, object o)
{
return o;
}
private static void FPSChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
//why do i need to update the binding manually? isnt that the point of a binding?
//
(obj as GlobalSettings).tbFPS.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
}
#endregion发布于 2011-06-25 01:45:05
不确定这是否是问题所在,但您应该传递"FPS“作为属性名,而不是"FPSProperty",如下所示:
public static readonly DependencyProperty FPSProperty =
DependencyProperty.Register("FPS", typeof(int), typeof(GlobalSettings),
new PropertyMetadata(MainWindow.appState.gSettings.fps,FPSChanged,FPSCoerce),
FPSValidate);发布于 2011-06-25 01:58:19
我还认为您需要将FrameworkPropertyMetadataOptions.BindsToWayByDefault添加到您的依赖属性注册中,否则您需要手动将TextBox.Text绑定的模式设置为TwoWay。
要使用FrameworkPropertyMetadataOptions,您需要在注册中使用FrameworkPropertyMetaData而不是PropertyMetadata:
public static readonly DependencyProperty FPSProperty =
DependencyProperty.Register("FPS", typeof(int), typeof(GlobalSettings),
new FrameworkPropertyMetadata(MainWindow.appState.gSettings.fps, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, FPSChanged, FPSCoerce),
FPSValidate);https://stackoverflow.com/questions/6471605
复制相似问题