WPF绑定到文本框不更新

3
我正在编写一个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
2个回答

4

不确定这是否是问题,但你应该将“FPS”作为属性名称传递,而不是“FPSProperty”,像这样:

public static readonly DependencyProperty FPSProperty =
    DependencyProperty.Register("FPS", typeof(int), typeof(GlobalSettings),
    new PropertyMetadata(MainWindow.appState.gSettings.fps,FPSChanged,FPSCoerce),
    FPSValidate);

1

我认为你需要在依赖属性注册中添加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);

好像在我实施了@CodeNaked的建议之后,它运行良好。我以为双向绑定本来就是默认设置。 - Max Ehrlich
如果它能正常工作,那太好了。我只是知道以前遇到过问题,其中选项未在注册中指定,除非我显式设置模式,否则我的绑定会失败。也许这是4.0中的变化? - sellmeadog

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接