【问题标题】:WPF Binding to textbox not updatingWPF绑定到文本框不更新
【发布时间】:2011-09-22 05:33:13
【问题描述】:

我正在编写一个 WPF 应用程序,并且我有一个文本框供用户输入用于视频播放的每秒帧数值。此文本框的值绑定到后面代码中的依赖属性(尝试像优秀的设计师一样遵循 MVVM)。我的问题是在外部更改 FPS 值时文本框不会自动更新。例如,用户可以使用滑块控制值。滑块正确更改了依赖项属性值,但文本框文本永远不会更新,当然,除非我使用 GetBindingExpression(..).UpdateTarget() 手动完成,这是我已经实现的等待更好的解决方案。有谁知道这是预期功能还是我设置错误?

谢谢, 最大

XAML 中的文本框标记:

<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

【问题讨论】:

    标签: c# wpf textbox binding dependency-properties


    【解决方案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 的建议后,它似乎工作正常,我认为无论如何绑定都是默认的
    • 如果它工作正常,那就太好了。我只知道在注册中未指定该选项并且我的绑定失败之前遇到了问题,除非我明确设置模式。也许这是 4.0 的变化?
    【解决方案2】:

    不确定这是否是问题所在,但您应该将“FPS”作为属性名称,而不是“FPSProperty”,如下所示:

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

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 2011-07-17
      相关资源
      最近更新 更多